Tim West
Tim West

Reputation: 77

Python convert dictionary values to list and append items

I have a dictionary of dictionaries named dictdict and it looks like:

dictdict = { 'key1': {'subkey1': 4, 'subkey2': 7}, 
             'key2': {'subkey1': 6, 'subkey2': 8} }

...and so on. dictdict has a few dozen keys and for each key a few dozen subkeys, with each subkey corresponding to a single integer value.

I want to append a list onto each individual value keeping the value that is already there as the first item in my new list of values. So the desired result would have the same dictionary of dictionaries structure as before, except instead of the subkeys corresponding to a single integer, they would correspond to a list containing integers and strings (so a list that contains my original value as the first item followed by various integers and strings).

I want to end up with something that looks like:

dictdict = { 'key1': {'subkey1': [4, 'apple', 37], 
                      'subkey2': [7, 'orange', 19]}, 
             'key2': {'subkey1': [6, 'kiwi', 76], 
                      'subkey2': [8, 'banana', 29]} }

When I try this...

#convert each nested value into a one item list
for key in dictdict:
    for subkey in dictdict[key]:
        dictdict[key][subkey] = [dictdict[key][subkey]] 

#now that our values are lists, append some items to the list
dictdict["key1"]["subkey1"].append('a1', a2) 

...it almost works, as I can append a list for each value (hooray!) however the first item in each list (my original value) is now a one item list of its own (oops!).

So I end up with

dictdict[key1][subkey1]

corresponding to this

[[4], 'a1', a2]

but I would like it to correspond to this

[4, 'a1', a2]

Also, it probably goes w/out saying, but I am a newbie.

Upvotes: 2

Views: 8402

Answers (2)

Alanyst
Alanyst

Reputation: 1410

You can use a dict comprehension, like so:

dictdict = {k:{kk:[vv] for (kk, vv) in v.iteritems()} for (k, v) in dictdict.iteritems()}

For example, if this was your initial dict:

>>> dictdict
{'a': {'mm': 4}, 'b': {'qq': 6}}

Then the result would be:

>>> dictdict = {k:{kk:[vv] for (kk, vv) in v.iteritems()} for (k, v) in dictdict.iteritems()}
>>> dictdict
{'a': {'mm': [4]}, 'b': {'qq': [6]}}

This gets you to the point where you can append items to the nested list(s). You can do that with += or extend() if you are appending another list, or with append() if you are appending a single element at a time.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304205

>>> dictdict = { 'key1': {'subkey1': 4, 'subkey2': 7}, 'key2': {'subkey1': 6, 'subkey2': 8} }
>>> dictdict["key1"]["subkey1"]
4
>>> for v1 in dictdict.values():
...     v1.update((k,[v]) for k,v in v1.iteritems())
... 
>>> dictdict["key1"]["subkey1"] += ['a1', 'a2']
>>> dictdict["key1"]["subkey1"]
[4, 'a1', 'a2']
>>> 

Upvotes: 4

Related Questions