【问题标题】:Getting a value from a particular dictionary from a list of dictionaries [duplicate]从字典列表中获取特定字典的值[重复]
【发布时间】:2020-04-18 00:56:00
【问题描述】:

假设我有以下字典列表:

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'},
]

如果用户输入月份为一月,他应该得到ID为001。

我试过了,但它只返回一个月份列表。

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

我需要直接来自密钥本身的 id。我怎样才能做到这一点?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您将拥有的内容转换为从月份映射到 id 的字典

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

      【讨论】:

        【解决方案3】:

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

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

        我在本地测试过这段代码,效果很好。

        【讨论】:

          【解决方案4】:

          应该是id而不是日期

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

          【讨论】:

          • 我只需要日期而不是 id,因为这是我的特殊要求
          【解决方案5】:

          使用if 在列表理解中进行过滤:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-08-30
            • 2017-10-23
            • 1970-01-01
            • 2017-10-23
            • 2022-01-14
            • 2021-01-16
            • 1970-01-01
            相关资源
            最近更新 更多