0

i have dictionary: dict = {key1:value1, key2:value2, key3:value3, key1:value4, key2:value5, key3:value6}

if i print keys from dictionary

def my_func():
    for key in dict:
        print(key)

it print only last 3 keys: for example:

   key1
   key2
   key3

but keys in dictionary can be same. Can you explain me why? if the key is the same, how to print like this:

key2:value2,value5

if it is possible. thank you in advance.

Merser5
  • 7
  • 3

2 Answers2

0

The keys in the dictionary cannot be the same. Statement key1:value4, effectively translates too:

x = {key1:value1, key2:value2, key3:value3}
x[key1] = value4

So your just overwriting the previous value. To have the desired effect you should implement a custom dict that stores the values in a list, and then some custom method to clear the list assuming that evey statement like x[key1] = value1 appends the value and does not replace it.

    class CustomDictOne(dict):
       def __init__(self):
          self._mydict = defaultdict(lambda:[])

       def __setitem__(self, key, item):
           self._mydict[key].append(item)

        def clear(self,key)
           self._mydict[key] = []

        def __getitem__(self, key):
           return self._mydict[key]

If you use a custom field name like I did _mydict you should also re-implement all the other methods:

CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42
0

To achieve a result like key2:value2,value5, you can use a collections.defaultdict.

Here's the example from the docs:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
SuperShoot
  • 9,880
  • 2
  • 38
  • 55