Ibrahim Hasnat
Ibrahim Hasnat

Reputation: 955

How can I store the same value in multiple keys?

Suppose I have a dictionary something like this:

odd_even = {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd'}

Here, all the odd number values are the same. I think assigning something like this is redundant.

I tried this way.

odd_even = {}
odd_even[1, 3, 5, 7, 9] = 'odd'
odd_even[2, 4, 6, 8] = 'even'

But I can't access the value using the key because they are stored as a tuple:

print(odd_even[1])

Is there any solution?

Upvotes: 1

Views: 147

Answers (5)

BaiJiFeiLong
BaiJiFeiLong

Reputation: 4665

There is not that grammer in python. Maybe loop is the best solution.

odd_even = dict()
for i in (1, 3, 5, 7, 9):
    odd_even[i] = "odd"
for i in (2, 4, 6, 8):
    odd_even[i] = "even"
odd_even = dict(sorted(odd_even.items()))
print(odd_even)

Or you can use this grammer:

odd_even = dict(sorted({**{x: "odd" for x in (1, 3, 5, 7, 9)}, **{x: "even" for x in (2, 4, 6, 8)}}.items()))
print(odd_even)

Upvotes: 0

Nicholas Hunter
Nicholas Hunter

Reputation: 1845

Dictionary comprehension:

odd_even = { key: 'odd' if key % 2 else 'even' for key in range(1, 11) }

Upvotes: 1

DYZ
DYZ

Reputation: 57105

There are many ways to skin this cat :) Say, a dictionary comprehension that looks up the right definition using the remainder (modulo) operator:

{i: ["even", "odd"][i % 2] for i in range(1, 10)}

Upvotes: 1

Yam Mesicka
Yam Mesicka

Reputation: 6601

You can use dictionary comprehension:

odd = {k: 'odd' for k in range(1, 10, 2)}
even = {k: 'even' for k in range(2, 10, 2)}
odd_even = {**odd, **even}  # or even.update(odd)

You can do both with one line:

odd_even = {k: 'odd' if k % 2 == 0 else 'even' for k in range(1, 10)}

Upvotes: 1

LPR
LPR

Reputation: 390

I don't think there's a quick way to do this. Your best bet is probably a for-loop:

odd_even = {}
for num in range(10):
    odd_even[num] = 'odd' if num&1 else 'even'
print(odd_even)
Out: {0: 'even', 1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd', 6: 'even', 7: 'odd', 8: 'even', 9: 'odd'}

Upvotes: 1

Related Questions