如何从dicts列表中通过dict值y获取dict值x

时间:2017-08-21 15:50:52

标签: python list dictionary

(Python 2.x)只有唯一键值对的dicts列表,按名称和名称进行alffabetically排序,名称也是唯一的:

dictlist = [
    {'name': 'Monty', 'has': 'eggs'},
    {'name': 'Terry', 'has': 'bacon'}    
    ]

我希望按名称获得给定名称。以下作品。

names = ['Monty', 'Terry']

print dictlist[names.index('Terry')]['has']

我创建了一个并行列表,其名称与dictlist中的名称的顺序相同,因此我可以使用列表中的 order 。 (我可以使用names循环填充for,但这与此处不相关)。

here,除其他外,我知道我可以这样做:

print next((d['has'] for d in dictlist if d['name'] == 'Terry'), None) 

但如果dictlist没有按名称排序,那只会更好。

所以我想知道是否有更简洁的方法来做到这一点,最好是一个至少与第一种方法一样可读的方法?

1 个答案:

答案 0 :(得分:5)

我根本不会使用列表。我会改用词典。

dictlist = {
    'Monty': {'has': 'eggs'},
    'Terry': {'has': 'bacon'}    
    }

这允许您按名称查找值:dictlist['Monty']['has']

如果你必须使用列表,那么我认为你有一个很好的解决方案。

相关问题