Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 824
navyad Avatar asked Jul 17 '26 11:07

navyad


1 Answers

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}]
like image 109
tobias_k Avatar answered Jul 20 '26 00:07

tobias_k