简体   繁体   English

Python-比较列表元素和字典元素

[英]Python - compare list elements with dictionary elements

I have a dictionary and a list. 我有字典和清单。 I need to compare the "id" tag of the dictionaries (integer) with the list elements. 我需要将字典(整数)的“ id”标记与列表元素进行比较。 Something like this: 像这样:

l = [[1], [7], [9]]

dict = {
"first":{
    "id": "0"
},
"second":{
    "id": "7"
},
"third":{
    "id": "4"
}
}

for i in l:
    for j in dict:
        if i == dict[j]["id"]:
            print("Yay!")
        else:
            print("Nay!")

I want to be able to check if any elements of list 'l' can be found in the "id" tags of dictionaries. 我希望能够检查在字典的“ id”标签中是否可以找到列表“ l”的任何元素。 How do I do that? 我怎么做?

I would do it like so: 我会这样做:

l = [[1], [7], [9]]

dict_ = {
         "first":{"id": "0"},
         "second":{"id": "7"},
         "third":{"id": "4"}
        }

ids = set(int(v['id']) for _, v in dict_.items())  # set of all ids for quick membership testing

l = [sublist for sublist in l if sublist[0] in ids]  # *
print(l)  # -> [[7]]

I am assuming that you want to modify (re-create) the l list with the items that meet your criteria. 我假设您想使用满足您条件的项目来修改(重新创建) l列表。


Notes: 笔记:

  1. Do not use dict as a variable name. 不要将dict用作变量名。 You are overwriting the Python built-in. 您正在覆盖内置的Python。
  2. There is no point to have a list of lists with the sublists being 1-element long. 列表列表的子列表的长度为1元素是没有意义的。 Flatten it ( l = [1, 7, 9] ) 展平( l = [1, 7, 9] 1,7,9 l = [1, 7, 9]

* alternatively, and if all elements in l are single-element lists, you can use the following which will most likely be significantly faster: *或者,如果l中的所有元素都是单元素列表,则可以使用以下方法,这可能会大大提高速度:

l = list(map(lambda x: [x], ids.intersection(x for y in l for x in y)))

As suggested by others please have ids as list instead list of lists. 根据其他人的建议,请使用ID作为列表,而不是列表列表。 And how about the solution with filter 以及filter的解决方案如何

lst_ids = [1, 7, 9]

my_dict = {
"first":{
    "id": "0"
},
"second":{
    "id": "7"
},
"third":{
    "id": "4"
}
}

filter(lambda k: int(my_dict[k]['id']) in lst_ids, my_dict)

This will return ['second'] that is matched keys of dict. 这将返回与字典键匹配的['second']

You can do it like this: 您可以这样做:

l = [[1], [7], [9]]

dict = {
         "first":{"id": "0"},
         "second":{"id": "7"},
         "third":{"id": "4"}
        }

for i in l:
    for j in dict:
        if i[0] == int(dict[j]["id"]):
            print("Yay!")
        else:
            print("Nay!")

You can also try this one-liner: 您也可以尝试以下一种方法:

l = [[1], [7], [9]]

d = {"first":{ "id": "0"},
     "second":{"id": "7"},
    "third":{"id": "4"}}

l = [elem for elem in l if elem[0] in list(int(value['id']) for value in d.values())]

print(l)

Output: 输出:

[[7]]

or alternatively you can do it using filter : 或者,您也可以使用filter

l = [[1], [7], [9]]

d = {"first":{ "id": "0"},
     "second":{"id": "7"},
    "third":{"id": "4"}}

resultValues = list(int(v['id']) for v in d.values())
l = list(filter(lambda i: i[0] in resultValues, l))

print(l)

Output: 输出:

[[7]]

Print Yay! Yay! and Nay! Nay! when -- convert to int and check in sub-list? 什么时候-转换为int并签入子列表?

l = [[1], [7], [9]]

dict1 = {
"first":{
    "id": "0"
},
"second":{
    "id": "7"
},
"third":{
    "id": "4"
}
}

for i in l:
    for j in dict1:
        if int(dict1[j]['id']) in i:
            print("Yay!")
        else:
            print("Nay!")

You can try this: 您可以尝试以下方法:

l = [[1], [7], [9]]

dict = {
"first":{
   "id": "0"
 },
"second":{
 "id": "7"
 },
 "third":{
    "id": "4"
 }
}
final_dicts = [{a:b} for a, b in dict.items() if [int(b['id'])] in l]
print "Yay!" if final_dicts else "Nay"

Output: 输出:

"Yay!"

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

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