Python 如何遍历嵌套的字典?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43752962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:22:31  来源:igfitidea点击:

How to iterate through a nested dict?

pythondictionary

提问by Arijit Panda

I have a nested python dictionarydata structure. I want to read its keys and values withoutusing collectionmodule. The data structure is like bellow.

我有一个嵌套的python dictionary数据结构。我想without使用collection模块读取它的键和值。数据结构如下。

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

I was trying to read the keys in the dictionary using the bellow way but getting error.

我试图使用波纹管方式读取字典中的键,但出现错误。

Code

代码

for key, value in d:
    print(Key)

Error

错误

ValueError: too many values to unpack (expected 2)

So can anyone please explain the reason behind the error and how to iterate through the dictionary.

那么任何人都可以解释错误背后的原因以及如何遍历字典。

采纳答案by Sunil Lulla

As the requested output, the code goes like this

作为请求的输出,代码是这样的

    d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

    for k1,v1 in d.iteritems(): # the basic way
        temp = ""   
        temp+=k1
        for k2,v2 in v1.iteritems():
           temp = temp+" "+str(k2)+" "+str(v2)
        print temp

In place of iteritems()you can use items()as well, but iteritems()is much more efficient and returns an iterator.

代替iteritems()你也可以使用items(),但iteritems()效率更高,并返回一个迭代器。

Hope this helps :)

希望这可以帮助 :)

回答by bharatk

keys()method returns a view object that displays a list of all the keys in the dictionary

keys()方法返回一个视图对象,该对象显示字典中所有键的列表

Iterate nested dictionary:

迭代嵌套字典:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

for i in d.keys():
    print i
    for j in d[i].keys():
        print j

OR

或者

for i in d:
    print i
    for j in d[i]:
        print j

output:

输出:

dict1 
foo
bar

dict2
baz 
quux

where iiterate main dictionary key and jiterate the nested dictionary key.

其中i迭代主字典键并j迭代嵌套字典键。

回答by Stephen Rauch

To get keys and values you need dict.items():

要获取您需要的键和值dict.items()

for key, value in d.items():
    print(key)

If you want just the keys:

如果你只想要钥匙:

for key in d:
    print(key)

回答by Ken Wei

Iterating through a dictionary only gives you the keys.

遍历字典只会给你键。

You told python to expect a bunch of tuples, and it tried to unpack something that wasn't a tuple (your code is set up to expect each iterated item to be of the form (key,value), which was not the case (you were simply getting keyon each iteration).

你告诉 python 期待一堆元组,它试图解包一些不是元组的东西(你的代码被设置为期望每个迭代项都是表单的(key,value),事实并非如此(你只是在key继续每次迭代)。

You also tried to print Key, which is not the same as key, which would have led to a NameError.

您还尝试打印Key,这与key, 会导致NameError.

for key in d:
    print(key)

should work.

应该管用。

回答by Fabio Caccamo

You could use benedict(a dictsubclass) and the traverseutility method:

您可以使用benedictdict子类)和traverse实用程序方法:

Installation: pip install python-benedict

安装: pip install python-benedict

from benedict import benedict

d = benedict({'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}})

def traverse_item(dct, key, value):
   print('key: {} - value: {}'.format(key, value))

d.traverse(traverse_item)

Documentation: https://github.com/fabiocaccamo/python-benedict

文档:https: //github.com/fabiocaccamo/python-benedict

回答by shivaraj karki

if given dictionary pattern has monotone format and keys are known

如果给定的字典模式具有单调格式并且键已知

dict_ = {'0': {'foo': 1, 'bar': 2}, '1': {'foo': 3, 'bar': 4}}
for key, val in dict_.items():
    if isinstance(val, dict):
        print(val.get('foo'))
        print(val.get('bar'))

in this case we can skip nested loop

在这种情况下,我们可以跳过嵌套循环