繁体   English   中英

Python - 如何通过键和返回值将列表与字典进行比较 - 然后放入列表

[英]Python - How to compare list with dictionary by keys and return values - put then into a list

我有一个例子:

birthday_persons = ['1966-06-26T11:50:25.558Z', '1949-10-09T00:25:51.304Z']

dates_ids = {'1966-06-26T11:50:25.558Z': 1, '1949-10-09T00:25:51.304Z': 2, '1992-11-21T06:28:32.563Z': 3}

dict key是出生日期,dict value是id号。

如果列表中的元素相等,我需要比较列表和字典键并返回 dict.value (id)。

我怎样才能做到这一点?

它基本上是:

for birthday_person in birthday_persons:
    if birthday_person in dates_ids:
        value = dates_ids.get(birthday_person)
        print(value)

您检查该人是否存在于字典中,然后获取值

for bday in birthday_persons:
  if bday in dates_ids.keys():
    return dates_ids[bday]

您可以简单地使用 for 循环来归档它

for bday in birthday_persons:
    print(dates_ids[bday])

暂无
暂无

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

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