Skip to content Skip to sidebar Skip to footer

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':

Solution 1:

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 inrange(0, len(items), 3)]
[{'aa': 1, 'bb': 2, 'cc': 3},
 {'dd': 4, 'ee': 5, 'ff': 6},
 {'gg': 7, 'hh': 8, 'ii': 9}]

Solution 2:

 new_dic_list = [k for k in dic.items()]
 for i inrange(0,len(new_dic_list),3):
       dc=dict(new_dic_list[i:i+3])

only works for multiples of 3. You can use modulus (% ) to simplify your method directly too

Solution 3:

Tested on Python 2.7.12:

defparts(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i + n]

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

keys = somedict.keys()
keys.sort()

for subkeys in parts(keys, 3):
    print({k:somedict[k] for k in subkeys})

Post a Comment for "Python: Create Sub-dictionary From Dictionary"