[英]How to get dict value x via dict value y from list of dicts
(Python 2.x) A list of dicts with only unique key-value pairs, sorted alfabetically by name, names are unique as well: (Python 2.x)仅包含唯一键值对的字典列表,按名称按字母顺序排序,名称也是唯一的:
dictlist = [
{'name': 'Monty', 'has': 'eggs'},
{'name': 'Terry', 'has': 'bacon'}
]
I want to get what a given name has, by name. 我想按名称获取给定名称的名称。 The following works.
以下作品。
names = ['Monty', 'Terry']
print dictlist[names.index('Terry')]['has']
I've made a parallel list with just names in the same order as the names in the dictlist, so I can make use of the order of the list. 我制作了一个并行列表,其中的名称与字典列表中的名称顺序相同,因此可以利用列表的顺序 。 (I could fill
names
with a for
loop, but that's not relevant here). (我可以用
for
循环填充names
,但这与此处无关)。
From here , among others, I know I could do this: 从这里 ,我知道我可以做到这一点:
print next((d['has'] for d in dictlist if d['name'] == 'Terry'), None)
but that's only better if dictlist isn't sorted by name. 但是,如果dictlist没有按名称排序,那才更好。
So I'm wondering if there isn't a more concise way of doing this, preferably one that's at least as readable as the first method? 所以我想知道是否没有更简洁的方法,最好是至少与第一种方法一样易读的方法?
I would not use a list at all. 我根本不会使用列表。 I would use a dictionary instead.
我会改用字典。
dictlist = {
'Monty': {'has': 'eggs'},
'Terry': {'has': 'bacon'}
}
This allows you to look up values by name like so: dictlist['Monty']['has']
这使您可以按名称查找值,如下所示:
dictlist['Monty']['has']
If you must use a list then I think you have a good solution as-is. 如果您必须使用列表,那么我认为您有一个好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.