简体   繁体   English

从 dict 中读取 python 中的 dict 列表

[英]Read from dict which is a list of dict in python

I want to check conditions of key values in a python dict.我想检查 python 字典中键值的条件。 My dict is a json response which would look like this:我的 dict 是一个 json 响应,看起来像这样:

result = {'arc': [{'empid':'S45',
                   'empname':'abc',
                   'empage':45,
                   'status':0,
                   'location': 'USA'},
                  {'empid':'S46',
                   'empname':'xyz',
                   'empage':34,
                   'status':1,
                   'location': 'USA'},
                  {'empid':'S47',
                   'empname':'oop',
                   'empage':36,
                   'status':1,
                   'location': 'UAE'}
                 ]}

I want to check the 'status' value and replace it as 'deactivate' if its 0. And this to be performed for 'location': 'USA' only.我想检查'status'值并将其替换为'deactivate',如果它为0。这仅针对'location'执行:'USA'。

Here is what I came with:这是我带来的:

data = result.values()
for i in data:
    for dict in i:
        for item in dict.values():
            print(item) 

Please help on how to check the condition by iterating over every key:value pair.请帮助了解如何通过遍历每个键:值对来检查条件。

First, you need to iterate over each element of the dict in result['arc'] , then if the status is 0 and location is USA replace the element with 'deactivate' .首先,您需要遍历result['arc']中字典的每个元素,然后如果状态为0且位置为USA ,则将元素替换为'deactivate'

for e in result['arc']:
    if e['location'] == 'USA' and e['status'] == 0:
        e['status'] = 'deactivate'
        
print(result)

The list you want to iterate over is not result.values() , it's result['arc'] .您要迭代的列表不是result.values() ,而是result['arc'] And you don't need to iterate over the values in the dictionaries.而且您不需要遍历字典中的值。

for arc in result['arc']:
    if arc['location'] == 'USA' and arc['status'] == 0:
        arc['status'] = 'deactivate'

Also, don't use dict or list as variable names, it replaces the built-in functions with those names.另外,不要使用dictlist作为变量名,它会用这些名称替换内置函数。

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

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