我有一个字典列表,如下例所示:
listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}]
我知道每个词典(以及其他键)中都存在'name',并且它是唯一的,并且不会出现在列表中的任何其他词典中。
我想通过使用键'name'来访问'two'和'one'的值。我想字典词典会最方便吗?像:
{'Foo': {'two': 'Baz', 'one': 'Bar'}, 'FooFoo': {'two': 'BazBaz', 'one': 'BarBar'}}
有了这个结构,我可以轻松地遍历名称,并通过使用名称作为键来获取其他数据。您对数据结构有任何其他建议吗?
我的主要问题是:进行这种转变的最好和最恐怖的方法是什么?
答案 0 :(得分:14)
d = {}
for i in listofdict:
d[i.pop('name')] = i
如果你有Python2.7 +:
{i.pop('name'): i for i in listofdict}
答案 1 :(得分:5)
dict((d['name'], d) for d in listofdict)
如果您不介意name
中剩余的dict
密钥,则是最简单的。
如果你想删除name
,你仍然可以在一行中轻松完成:
dict(zip([d.pop('name') for d in listofdict], listofdict))