我有一个看起来像下面这样的字典(尽管有超过 150 万对):
{'key1' : 10,
'key2' : 20,
'key3' : [30,40],
'key4' : 50,
'key5' : [60,70,80],
'key6' : 90}
我 99% 的键都有一个值,但是对于具有值数组的键。我想改为返回最后一个元素。
因此我生成的字典将被扁平化且独一无二;
{'key1' : 10,
'key2' : 20,
'key3' : 40,
'key4' : 50,
'key5' : 80,
'key6' : 90}
根据我的搜索,我认为列表理解可能是最好的方法,但我只是不确定该怎么做。特别是因为并非每个键都包含相同的数据类型。
谢谢
最佳答案
一个简单的字典理解就可以:
d = {'key1': 10,
'key2': 20,
'key3': [30, 40],
'key4': 50,
'key5': [60, 70, 80],
'key6': 90}
d = {k: v if not isinstance(v, list) else v[-1] for k, v in d.items()}
# ^ if v is not a list taking v as it, otherwise taking the last element
print(d)
输出
{'key1': 10, 'key2': 20, 'key3': 40, 'key4': 50, 'key5': 80, 'key6': 90}
当然反过来也行:
d = {k: v[-1] if isinstance(v, list) else v for k, v in d.items()}
关于python - Dict - 如果每个键有多个值,则提取最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783542/