-1

I have dictionaries that I've created using a loop:

for (obj1, obj2), df in df2.groupby(['a', 'b']):
    obj_dict = (df
                .query('a == @obj1')
                .query('b == @obj2')
                .set_index('b')['c']
                .to_dict()
               )
    print(obj_dict)

This is the outcome:

{'2': '3'}
{'5': '6'}
{'8': '9'}

I want to merge these dictionaries into one that looks like this:

{'2': '3','5': '6','8': '9'}

I've tried using .update as suggested here however that does not seem to work:

for (obj1, obj2), df in df2.groupby(['a', 'b']):
    obj_dict = (df
                .query('a == @obj1')
                .query('b == @obj2')
                .set_index('b')['c']
                .to_dict()
               )
    print(obj_dict)
    result = {}
    for d in obj_dict:
        print(d)
        result.update(d)

Result:

{'2': '3'}
2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-107-ca40733d19d7> in <module>
     10     for d in obj_dict:
     11         print(d)
---> 12         result.update(d)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I don't really understand why d in the result is only the key and not the actual dictionary.

AriesNinja
  • 55
  • 10
  • If you iterate over a dictionary, you’ll get an iterator over its keys. If you want both key and value then iterate over dict.items(). – jarmod Nov 15 '20 at 20:31

2 Answers2

1

d is the key because you're iterating of the dictionary itself, not a list of dictionaries. The a python feature (not a bug). I would change the code around a little.

We define a new obj_dict which will contain all merged data. Then we update it with the new_dict created from the data frames.

obj_dict = {}
for (obj1, obj2), df in df2.groupby(['a', 'b']):
    new_dict = (df
                .query('a == @obj1')
                .query('b == @obj2')
                .set_index('b')['c']
                .to_dict()
               )
    obj_dict.update(new_dict)
Exelian
  • 5,749
  • 1
  • 30
  • 49
0

It looks like you have things just a bit out of order. Try this:

result = {}
for (obj1, obj2), df in df2.groupby(['a', 'b']):
    obj_dict = (df
                .query('a == @obj1')
                .query('b == @obj2')
                .set_index('b')['c']
                .to_dict()
               )
    print(obj_dict)
    result.update(obj_dict)
anon01
  • 10,618
  • 8
  • 35
  • 58