【问题标题】:How to get other values in dictionary then one value equals如何在字典中获取其他值然后一个值等于
【发布时间】:2020-05-02 12:29:13
【问题描述】:

我有一个字典列表。当另一个字典对的值为'x'时,我想获取字典对的值

alphabets = [
              {"name": "abc", "value": "first_three"}, 
              {"name": "mno", "value": "middle"}, 
              {"name": "xyz", "value": "last_three"}
            ]

abc 时如何获得first_three

这就是我正在做的,但我没有得到任何结果。

res = [ sub['name'] for sub in d['alphabets'] ]
            if res == 'abc':
               val = [ sub['value'] for sub in d['alphabets'] ]
               print(val)

我没有得到任何结果。 name == 'abc时如何获取first_three

【问题讨论】:

  • 试试这样的:values_where_names_are_abc = [_['value'] for _ in list_dict if _['name'] == 'abc'].
  • 如果您编辑您的帖子并与您提到的变量名称保持一致会很好。您的字典列表是list_dict,但在您的代码中您提到了d['alphabet']sub['name']。这让你很难理解你想要实现的逻辑。
  • 如果名称是唯一的,我建议使用以名称为键的字典。

标签: python python-3.x list dictionary for-loop


【解决方案1】:

使用列表推导:

res = [d['value'] for d in list_dict if d['name'] == 'abc']

>>> print(res)
['first_three']

【讨论】:

  • 应该注意这个列表推导没有任何中断条件,所以对于长列表,即使找到正确的名称它也会继续查找(假设名称在列表中是唯一的)。
【解决方案2】:
for d in list_dict:
  if d['name'] == 'abc':
    print d['value']

我不太了解您在代码中使用的不起作用的策略,但我可以告诉您的一件事是res == 'abc' 永远不会是真的,因为您将res 设置为在线列表一个。

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多