Scrappy Coco :
I have a dictionary, the keys of which are:
{'A', 'B', 'C', 'D'}
and some examples of list values:
1- [(33.0, 134), (54.0, 113), (21.0, 120)]
2- [(25.0, 153)]
3- [()]
I want to apply the list values to the dictionary keys in order. The expected output will be in case 1-:
{'A' : 33.0,
'B' : 134,
'C' : 54.0,
'D' : 113}
in case 2-:
{'A' : 25.0,
'B' : 153,
'C' : NaN,
'D' : NaN}
in case 3-:
{'A' : NaN,
'B' : NaN,
'C' : NaN,
'D' : NaN}
How can I do this?
CDJB :
As a dictionary comprehension - substitute 'NaN'
for np.nan
if that's the value you're after.
>>> keys = ['A', 'B', 'C', 'D']
>>> l = [(33.0, 134), (54.0, 113), (21.0, 120)]
>>> dict(zip(keys,([x for sl in l for x in sl]+['NaN']*len(keys))[:len(keys)]))
{'A': 33.0, 'B': 134, 'C': 54.0, 'D': 113}
>>> l = [(25.0, 153)]
>>> dict(zip(keys,([x for sl in l for x in sl]+['NaN']*len(keys))[:len(keys)]))
{'A': 25.0, 'B': 153, 'C': 'NaN', 'D': 'NaN'}
>>> l = [(,)]
>>> dict(zip(keys,([x for sl in l for x in sl]+['NaN']*len(keys))[:len(keys)]))
{'A': 'NaN', 'B': 'NaN', 'C': 'NaN', 'D': 'NaN'}
Explanation:
We use zip()
to zip the keys list of size n
with the flattened list of tuples, appending a list of n
'NaN'
values to the end, and then chopping off the first n
values. The dict()
constructor accepts a zipped list as an argument.