[英]Python: create sub-dictionary from dictionary
I have a python dictionary, say 我有一个python字典,说
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 我想列出长度为3的子字典元素,例如
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? 任何pythonic方式做同样的事情?
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, eg by key.
字典中的条目是无序的,因此,如果您希望块具有一定的顺序,请对项进行排序,例如,按键排序。 Now, you can use a list comprehension, slicing chunks of 3 from the list of items and turning them back into dictionaries.
现在,您可以使用列表推导,从项目列表中切出3个大块,然后将它们变回字典。
>>> 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}]
new_dic_list = [k for k in dic.items()]
for i in range(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 仅适用于3的倍数。您也可以使用模数(%)直接简化方法
Tested on Python 2.7.12: 在Python 2.7.12上测试:
def parts(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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.