简体   繁体   中英

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) :

{'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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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