Python:从字典创建子字典 [英] Python: create sub-dictionary from dictionary

查看:185
本文介绍了Python:从字典创建子字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python字典,说

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

我想列出长度为3的子字典元素,如

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

我附带以下代码:

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

任何pythonic的方式来做同样的事情?

解决方案

您可以这样尝试:首先,从字典获取项目,作为键值对列表。字典中的条目是无序的,因此如果您想要块具有某种顺序,请对项目进行排序,例如按键。现在,您可以使用列表解析,从项目列表中切片3,并将其转回词典。

 > ;>> items = sorted(dic.items())
>>>对于范围(0,len(items),3)中的i的[dict(items [i:i + 3])]
[{'aa':1,'bb':2,'cc' },
{'dd':4,'ee':5,'ff':6},
{'gg':7,'hh':8,'ii':9}


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?

解决方案

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}]

这篇关于Python:从字典创建子字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆