2
>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}

It has same keys 'a'

and I want to get all values from this dic

but when I use

>>> dic.get('a')

It only returns

['4a','5a']

How can I get all 'a' key's values from it?

I have thought to using repetitive statement to check all keys, but it seems inefficient

user4315272
  • 143
  • 1
  • 2
  • 13

3 Answers3

3

A dictionary can't store duplicate keys. One way around is to store lists or sets inside the dictionary. I'd recommend you to store values in a set pointing same keys.

>>> from collections import defaultdict

>>> dic = defaultdict(list)

>>> dic['a'].extend(['1a','2a','3a'])
>>> dic['a'].extend(['4a','5a'])
>>> dic['b'].extend(['1b','2b'])
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
2

You say:

>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}
It has same keys 'a'

no it doesn't:

>>> dic = {'a': ['1a','2a','3a'],'b': ['1b','2b'], 'a' : ['4a','5a']}
>>> dic
{'a': ['4a', '5a'], 'b': ['1b', '2b']}

the first occurrence of key 'a' has simply disappeared, "trampled over" by the second occurrence of the same key.

I doubt you're building dic as a dict literal like this (I think such a literal should raise an exception, because it makes absolutely no sense, but, alas, it doesn't) -- can you show us the actual code you're using instead in order to build that dict? Then we might suggest how to actually build the dict you want!-)

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0

Python dictionary doesn't support duplicate keys, check this thread for a solution to achive this, make dictionary with duplicate keys in python

Community
  • 1
  • 1
flynn
  • 23
  • 1
  • 6