【问题标题】:How to access the dictionary from a list of dictionaries using one key/value pair of the dictionary that I want to fetch如何使用我要获取的字典的一个键/值对从字典列表中访问字典
【发布时间】:2021-10-18 20:57:46
【问题描述】:

我有一个字典列表,它们都有相同的键。我有一个键的特定值,并且想要访问/打印包含该特定值的字典。除了循环整个列表,检查键的相应值并使用 if 语句将其打印出来之外,我想不出任何办法,也就是说,如果给定的值与键匹配。

for enrollment in enrollments:
    if enrollment['account_key'] == a:
        print(enrollment)
    else:
        continue

这似乎并不是处理任务的最有效方式。有什么更好的解决方案?

【问题讨论】:

  • 您打算多次执行此操作吗?还是只有一次?请提供一些示例数据
  • 你是对的,这不是处理任务的最有效方式,但这与你的数据结构不利于这种类型的操作这一事实有关。执行此任务的正确方法是使用允许此类查找的更合适的数据结构,例如字典字典,假设您的 account_key 值都是唯一的。
  • 你不需要 else/continue
  • 鉴于您的数据结构,别无选择。怎么会有?如果不检查所有值,您不可能知道该值在哪里。如果您知道确实有一个,您可以随时在print 之后break 停止进一步查找。
  • 如果替代方案是print(“\n”.join([v for v in enrollments if v.get(‘account_key’)==‘a’])),我宁愿使用三行for循环。

标签: python python-3.x dictionary


【解决方案1】:

一些选项:

1- 像这里一样使用循环,尽管如果没有 continue 可以更简单地编写。

for enrollment in enrollments:
    if enrollment['account_key'] == a:
        print(enrollment)

2- 使用生成器表达式和next

enrollment = next(e for e in enrollments if e['account_key'] == a)
print(enrollment)

3- 将字典列表转换为字典字典。如果您必须多次执行此操作并且每个account_key只有一个值,这是一个不错的选择

accounts = {
    enrollment['account_key']: enrollment
    for enrollment in enrollments
}
print(accounts[a])

4- 同上,但是如果同一个键有多个值,你可以使用字典列表的字典。

accounts = defaultdict(list)
for enrollment in enrollments:
    accounts[enrollment['account_key']].append(enrollment)

for enrollment in accounts[a]:
    print(enrollment)

【讨论】:

    【解决方案2】:

    您可以使用推导式(迭代器)来获取符合您的条件的字典子集。无论如何,这将是一个顺序搜索过程。

    enrolments = [ {'account_key':1, 'other':99},
                   {'account_key':2, 'other':98},
                   {'account_key':1, 'other':97},
                   {'account_key':1, 'other':96},
                   {'account_key':3, 'other':95} ]
    
    a = 1
    found = (d for d in enrolments if d['account_key']==a)
    print(*found,sep="\n")
    
    {'account_key': 1, 'other': 99}
    {'account_key': 1, 'other': 97}
    {'account_key': 1, 'other': 96}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-21
      • 2013-08-22
      • 1970-01-01
      相关资源
      最近更新 更多