英文:
Convert Python list of dicts to mapping of key to rest of dict
问题
让我们假设我有以下列表:
l = [
{"a": 10, "b": 100, "c": 100},
{"a": 20, "b": 100, "c": 100},
{"a": 30, "b": 100, "c": 100},
]
我知道"a"
在每个条目中是唯一的:
assert len({x["a"] for x in l}) == len(l)
我想生成一个将"a"
值映射到每个条目的其余部分的字典,所以我的最终结果是以下字典:
{
10: {"b": 100, "c": 100},
20: {"b": 100, "c": 100},
30: {"b": 100, "c": 100},
}
到目前为止,我想到了以下方法:
{x["a"]: {k: v for k, v in x.items() if k != "a"} for x in l}
这是写这个的最好方式吗?还是有更好的方法或我漏掉的内置函数?
英文:
Let's say I have the following list:
l = [
{"a": 10, "b": 100, "c": 100},
{"a": 20, "b": 100, "c": 100},
{"a": 30, "b": 100, "c": 100},
]
I know "a"
is unique in each item:
assert len({x["a"] for x in l}) == len(l)
I want to generate a mapping of the "a"
value to the rest of each item so my end result is the following dictionary:
{
10: {"b": 100, "c": 100},
20: {"b": 100, "c": 100},
30: {"b": 100, "c": 100},
}
So far I've come up with the following:
{x["a"]: {k: v for k, v in x.items() if k != "a"} for x in l}
Is this the best way to write this? Or is there a better way or a built in function that I'm missing?
答案1
得分: 4
也许你想要使用 dict.pop
?
out = {d.pop('a'): d for d in l}
print(out)
打印结果:
{10: {'b': 100, 'c': 100}, 20: {'b': 100, 'c': 100}, 30: {'b': 100, 'c': 100}}
英文:
Maybe dict.pop
is what you want?
out = {d.pop('a'): d for d in l}
print(out)
Prints:
{10: {'b': 100, 'c': 100}, 20: {'b': 100, 'c': 100}, 30: {'b': 100, 'c': 100}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论