如何在python 2.7x中展平嵌套字典
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在python 2.7x中展平嵌套字典,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1647字,纯文字阅读大概需要3分钟。
内容图文
![如何在python 2.7x中展平嵌套字典](/upload/InfoBanner/zyjiaocheng/692/0f003471db5e4fbc8a6155dc1185dc99.jpg)
我有一个类似下面的嵌套字典.我该如何展平,以便每个botten级别都有一个列表列表?
例如
[[en,Chome,ChromeOS,null,180, '0', '0', '0', '0',
[en, Linux,null,27868, '0', '0', '0', '0'],
...
]
输入
test = {u'en': {'Chrome': {'ChromeOS': {u'null': [180, '0', '0', '0', '0']},
'Linux': {u'null': [27868, '0', '0', '0', '0']},
'Macintosh': {u'null': [330991, '0', '0', '0', '0']},
'Windows': {u'null': [3296819, '0', '0', '0', '0']}},
'Firefox': {'Linux': {u'null': [18076, '0', '0', '0', '0']},
'Macintosh': {u'null': [168444, '0', '0', '0', '0']},
'Windows': {u'null': [1517775, '0', '0', '0', '0']}},
'Konqueror': {'Linux': {u'null': [9, '0', '0', '0', '0']}},
'Microsoft Internet Explorer': {'Windows': {u'null': [3060154,
'0',
'0',
'0',
'0']}},
'Opera': {'Linux': {u'null': [2274, '0', '0', '0', '0']},
'Macintosh': {u'null': [1573, '0', '0', '0', '0']},
'Windows': {u'null': [38589, '0', '0', '0', '0']}},
'Opera Mobile': {'Linux': {u'null': [5807, '0', '0', '0', '0']},
'Windows': {u'null': [1, '0', '0', '0', '0']}},
'Safari': {'Blackberry': {u'null': [530, '0', '0', '0', '0']},
'Linux': {u'null': [292862, '0', '0', '0', '0']},
'Macintosh': {u'null': [618641, '0', '0', '0', '0']},
'Windows': {u'null': [36359, '0', '0', '0', '0']}},
'SeaMonkey': {'Linux': {u'null': [120, '0', '0', '0', '0']},
'Macintosh': {u'null': [224, '0', '0', '0', '0']},
'Windows': {u'null': [1890, '0', '0', '0', '0']}},
'WOSBrowser': {'Linux': {u'null': [687, '0', '0', '0', '0']}},
'null': {'null': {u'null': [15559, '0', '0', '0', '0']}}}}
解决方法:
def flatten_dict(d):
for k,v in d.items():
if isinstance(v, dict):
for item in flatten_dict(v):
yield [k]+item
else:
yield v
flattened = list(flatten_dict(test))
内容总结
以上是互联网集市为您收集整理的如何在python 2.7x中展平嵌套字典全部内容,希望文章能够帮你解决如何在python 2.7x中展平嵌套字典所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。