navyad navyad - 3 years ago 50
Python Question

Python: create sub-dictionary from dictionary

I have a python dictionary, say

dic = {"aa": 1,
"bb": 2,
"cc": 3,
"dd": 4,
"ee": 5,
"ff": 6,
"gg": 7,
"hh": 8,
"ii": 9}


I want to make list of sub-dictionary elements of having length 3 like

dic = [{"aa": 1, "bb": 2, "cc": 3},
{"dd": 4, "ee": 5, "ff": 6},
{"gg": 7, "hh": 8, "ii": 9}]


I came with following code :

dic = {"aa": 1,
"bb": 2,
"cc": 3,
"dd": 4,
"ee": 5,
"ff": 6,
"gg": 7,
"hh": 8,
"ii": 9}
i = 0
dc = {}
for k, v in dic.items():
if i==0 or i==3 or i==6:
dc = {}
dc[k] = v
if i==2 or i==5 or i==8:
print dc
i = i + 1


Output:

{'aa': 1, 'ee': 5, 'hh': 8}
{'cc': 3, 'bb': 2, 'ff': 6}
{'ii': 9, 'gg': 7, 'dd': 4}


any pythonic way to do same stuff?

Answer Source

You can try like this: First, get the items from the dictionary, as a list of key-value pairs. The entries in a dictionaries are unordered, so if you want the chunks to have a certain order, sort the items, e.g. by key. Now, you can use a list comprehension, slicing chunks of 3 from the list of items and turning them back into dictionaries.

>>> items = sorted(dic.items())
>>> [dict(items[i:i+3]) for i in range(0, len(items), 3)]
[{'aa': 1, 'bb': 2, 'cc': 3},
 {'dd': 4, 'ee': 5, 'ff': 6},
 {'gg': 7, 'hh': 8, 'ii': 9}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download