从词典列表中从特定词典获取值

时间:2019-12-28 13:06:19

标签: python python-3.x

假设我有以下词典列表:

months = [
    {'id':'001','date':'January'},
    {'id':'002','date':'February'},
    {'id':'003','date':'March'},
    {'id':'004','date':'April'},
    {'id':'005','date':'May'},
    {'id':'006','date':'June'},
    {'id':'007','date':'July'},
    {'id':'008','date':'August'},
    {'id':'009','date':'September'},
    {'id':'010','date':'October'},
    {'id':'011','date':'November'},
    {'id':'012','date':'December'},
]

如果用户输入月份为1月,则其ID为001。

我尝试过此操作,但它只返回了一个月列表。

res = [ mon['date'] for mon in months]

我直接需要密钥本身的ID。我该如何实现?

5 个答案:

答案 0 :(得分:6)

您可以将月份用作字典中的键:

res = {mon['date']: mon['id'] for mon in months}
print(res['January'])

答案 1 :(得分:1)

您将拥有的内容转换为从几个月映射到ID的字典

new_dict = {item['date']: item['id'] for item in months}

答案 2 :(得分:1)

我希望这段代码对您有用。

month_name = input("Enter month name.")
dic = next(item for item in months if item["date"] == month_name)
id = dic["id"]
print(id)

我已经在本地测试了此代码,效果很好。

答案 3 :(得分:0)

它应该是id而不是日期

res = [ mon['id'] for mon in months]

答案 4 :(得分:0)

使用if在列表理解范围内进行过滤:

id = [m['id'] for m in months if m['date'] == 'January'][0]