将Python字典列表转换为键映射到字典的其余部分

huangapple go评论55阅读模式
英文:

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}}

huangapple
  • 本文由 发表于 2023年6月9日 03:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435305.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定