简体   繁体   English

Dict-如果每个键有多个值,则提取最后一个元素

[英]Dict - If more than one value per key, extract the last element

I have a dict the looks like the following (though there is 1.5mil+ pairs) : 我有一个字典看起来像下面(尽管有150万+对):

{'key1' : 10,
'key2' : 20,
'key3' : [30,40],
'key4' : 50,
'key5' : [60,70,80],
'key6' : 90}

99% of my keys have a single value, however for the keys that have an array of values.. I'd like to instead return the last element. 我的键中有99%具有单个值,但是对于具有值数组的键。我想返回最后一个元素。

So my resulting dict would be flattened and unique; 因此,我得出的结论将变得扁平而独特。

 {'key1' : 10,
'key2' : 20,
'key3' : 40,
'key4' : 50,
'key5' : 80,
'key6' : 90}

From my searches I think a list comprehension would likely be the best way but I'm just not sure how to do it. 从我的搜索中,我认为列表理解可能是最好的方法,但是我不确定该怎么做。 Particularly because not every key contains the same data type. 特别是因为并非每个键都包含相同的数据类型。

Thanks 谢谢

A simple dict comprehension will do: 一个简单的dict理解即可:

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)

Outputs 产出

{'key1': 10, 'key2': 20, 'key3': 40, 'key4': 50, 'key5': 80, 'key6': 90}

Of course the inverse will also work: 当然,逆运算也可以:

d = {k: v[-1] if isinstance(v, list) else v for k, v in d.items()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM