根据字典Python的键值检查列表中的值

时间:2020-04-22 14:15:14

标签: python list dictionary compare key-value

我有两个数据源,一个是列表,另一个是字典列表。 我的数据如下所示:

need_placeholder = ['1200', '1300', '1400']
ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"}, 
           {"Name": "C", "ID": "1400"}]

我需要检查need_placeholders项是否等于ID中的ad_dict值。这是我的脚本:

for item in need_placeholder:
    adpoint_key = item 
    for index, my_dict in enumerate(ad_dict):
        if my_dict["ID"] == adpoint_key:
            continue
        else:    
            print(f'No key exists for {adpoint_key}')

输出为:

No key exists for 1200
No key exists for 1200
No key exists for 1200
No key exists for 1300
No key exists for 1300
No key exists for 1300

我想要的输出是:

No key exists for 1200
No key exists for 1300

如何在不循环浏览字典或列表的情况下比较这些值?

5 个答案:

答案 0 :(得分:1)

您的else在循环中的错误位置。对于每个输出,该内循环运行几次。如果您首先将ID的值放入集合中,则可以完全避免该循环:

need_placeholder = ['1200', '1300', '1400']
ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"}, {"Name": "C", "ID": "1400"}]

ad_values = set(d['ID'] for d in ad_dict)

for v in need_placeholder:
    if v not in ad_values:
        print(f'no key exits for {v}')

打印:

no key exits for 1200
no key exits for 1300

如果顺序不重要,则可以将整个操作作为一个单独的设置操作完成:

for v in set(need_placeholder) - ad_values:
    print(f'no key exits for {v}')

答案 1 :(得分:1)

您可以尝试一下。

>>> need_placeholder = ['1200', '1300', '1400']
>>> ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"}, 
               {"Name": "C", "ID": "1400"}]
>>> keys={d['ID'] for d in ad_dict} # Set of all unique ID values
>>> [key for key in need_placeholder if not key in keys]
# ['1200', '1300']

您可以使用itertools.filterfalse

list(filterfalse(lambda x:x in keys, need_placeholder))
# ['1200', '1300']

如果您不在乎订单

set(need_placeholder)-keys
# {'1300', '1200'}

使用all

>>> for key in need_placeholder:
...     if all(key != d['ID'] for d in ad_dict):
...         print(f'No key exists for {key}')
...
No key exists for 1200
No key exists for 1300

使用for-else

>>> for key in need_placeholder:
...     for d in ad_dict:
...             if key==d['ID']:
...                     break
...     else:
...             print(f'No key {key}')
...
No key 1200
No key 1300

答案 2 :(得分:1)

allowed_values = {dic["ID"] for dic in ad_dict}

for item in need_placeholder:
    if item not in allowed_values:
        print(f'No key exists for {item}')

答案 3 :(得分:0)

执行此操作的一种快速方法是使用嵌套列表理解

2020-03-24

答案 4 :(得分:0)

for item in need_placeholder:
    adpoint_key = item
    duplicate_exist = False # flag that will be update if key exists
    for index, my_dict in enumerate(ad_dict):
        if my_dict["ID"] == adpoint_key:
            duplicate_exist = True    # flag is updated as key exists
    not duplicate_exist and print(f'No key exists for {adpoint_key}') # for all non duplicate print function is invoked at the end of inner loop