Skip to content Skip to sidebar Skip to footer

Python Dictionary W/ 2 Keys?

Can I have a python dictionary with 2 same keys, but with different elements?

Solution 1:

No, but you can add 2 elements to one 1 key. dictionary = {‘a’, [b,c]}. You would use a list object to have multiple values in a dictionary.


Solution 2:

No.

The normal way to do this is with a defaultdict:

dd = defaultdict(list)

dd['Your mother\'s key'].append('A')
dd['Your mother\'s key'].append('B')

dd['Your mother\'s key'] #=> ['A', 'B']

If this isn't quite sufficient, you can create your own class.


Solution 3:

If you want, you can create a list of "pair" tuples, like:

thelist = [('foo', 'first_foo'), ('foo', 'second_foo'), ('bar', 'not_foo')]

Then you can retrieve something equivalent to thelist['foo'] with this ugly hack:

for pair in thelist:
    if pair[0] == 'foo':
        print pair[1]

and get

first_foo
second_foo

Post a Comment for "Python Dictionary W/ 2 Keys?"