如何将字典与字典列表进行比较

时间:2020-07-26 11:44:09

标签: python dictionary

我有一个字典清单和一本字典。我需要将列表中的每个字典与单独的字典进行比较,并在匹配时打印出特定的键。

例如:

# The list of dictionaries is created out of csv file
list_of_dicts = {
    OrderedDict([('name', 'Alice'), ('A', '2'), ('G', '8'), ('C', '3')])
    OrderedDict([('name', 'Bob'), ('A', '4'), ('G', '1'), ('C', '5')])
    OrderedDict([('name', 'Charlie'), ('A', '3'), ('G', '2'), ('C', '5')])
}

sep_dict = {'name': 0, 'A': 4, 'G': 1, 'C': 5}

for i in list_of_dicts:
    if i == sep_dict:
        sep_dict['name'] = i['name']

比较之后,我想根据list_of_dicts更新sep_dict'name'键。我知道互联网上也有类似的问题,但是我对python编程还是陌生的,无法弄清楚如何实现它们。我已经尝试过简单的for循环和if语句,但是它们不起作用。我也尝试过转移字典进行设置,但无法理解其背后的逻辑。

1 个答案:

答案 0 :(得分:0)

# list of dictionaries
list_of_dicts = [
    {"name": "john", "age": 30, "colour": "red"},
    {"day": 1, "month": 7, "year": 2010},
    {"item": "apple", "cost": 55, "name": "pink lady"},
]

sep_dict = {'name': 0, 'A': 4, 'G': 1, 'C': 5}

for dictionary in list_of_dicts:
    for key in dictionary:
        if key in sep_dict:
            print(key)
            # update sep_dict however you like, although note that
            # there may be multiple dictionaries with the same key
            # in list_of_dicts
            sep_dict[key] = dictionary[key]

这与您尝试执行的操作类似,只是比较sep_dict中的键和list_of_dicts中的每个字典。


您可以遍历键值对:

for dictionary in list_of_dicts:
    for key,value in dictionary.items():
        if key in sep_dict:
            print(key, ":", value)

或者,您可以考虑使用列表推导来获取与sep_dict共享密钥的所有键值对的列表,然后对它进行任何操作。这基本上与前面的代码块相同,但是更加简洁。

common = [(k,d[k]) for d in list_of_dicts for k in sep_dict if k in d]
#> [('name', 'john'), ('name', 'pink lady')]
for k,v in common:
    print(k, ":", v)
#> name : john
#> name : pink lady