简体   繁体   English

python:如何使用循环访问嵌套字典中的值

[英]python: how to access values in nested dictionaries using loops

Given the following dictionary in python.给定以下 Python 字典。

dict = {'site1': {'status': 200}, 'site2': {'status': 200}, 'site3': {'status': 200}}

How can I iterate and access the values of a sub dictionary?如何迭代和访问子字典的值?

for sub in dict.items():
    print(sub["status"])

gives error: tuple indices must be integers or slices, not str给出错误:元组索引必须是整数或切片,而不是 str

Desired outcome: print 3 strings indicating site status for each sub dict.预期结果:打印 3 个字符串,指示每个子字典的站点状态。

items() returns a tuple of (key, value), so for loop should like this: items()返回一个 (key, value) 元组,所以 for 循环应该是这样的:

dct = {'site1': {'status': 200}, 'site2': {'status': 200}, 'site3': {'status': 200}}

for key, value in dct.items():
    print(value['status'])

Out:出去:

200
200
200

dict.items() returns iterable of tuple pairs (key, value) . dict.items()返回可迭代的元组对(key, value) In here you want to further index a value , so you should either do:在这里你想进一步索引一个value ,所以你应该这样做:

for sub in dict.values():
    print(sub["status"])

to iterate values only.仅迭代值。

Or:或者:

for key, sub in dict.items():
    print(sub["status"])

to unpack the tuple (that's what one usually does when dealing with dict.items() ).解包元组(这是处理dict.items()时通常所做的)。

Of course you could also index the tuple first - sub[1]["status"] but it's not as readable.当然,您也可以先索引元组 - sub[1]["status"]但它不那么可读。


PS You should never name your dicts just dict (nor lists list ) - it's a build-in name used to denote the type. PS 你永远不应该把你的字典命名为dict (也不应该列出list )——它是一个用于表示类型的内置名称。 Changing it might introduce bugs later on.更改它可能会在以后引入错误。

for sub in dict.values():
  print(sub)
#that will gives you list of dictionaries
{'status': 200} {'status': 200} {'status': 200} 

Now to print key values现在打印键值

for sub in dict.values():
   print(sub['status'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM