Home > other >  create a sub-dict with first element in dict for every key
create a sub-dict with first element in dict for every key

Time:12-07

I have a dictionary containing different lists, I would need a fast & efective way to create a new dictionary containing same keys (better if I can be independent of key names) and one value of the list let's say the i-th

one example

 someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]} 

then the first elements (i=0) should return

subdict = {'key1':1,'otherkey':0.256}

the third element would be:

subdict = {'key1':3,'otherkey':0.487}

I could do some for key,val in someDict... to create new dict but i'm not sure it's the best option

CodePudding user response:

Depending on what you need the new dict objects for, a pandas dataframe may be the best choice. It will generally be more performant for table-like operations. For instance, if your plan is to put those dicts in a list, the datatrame could be a good fit.

>>> import pandas as pd
>>> someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]} 
>>> df = pd.DataFrame(someDict)
>>> df
   key1  otherkey
0     1     0.256
1     2     0.221
2     3     0.487
3     4     0.454
4     5     0.555

CodePudding user response:

Try this:

def ith_val_subdict(input_dict, i):
    return {k: v[i] for k, v in input_dict.items()}

Example:

someDict = {'key1': [1,2,3,4,5],'otherkey': [.256,.221,.487,.454,.555]}

subdict_0 = ith_val_subdict(someDict, 0)
print(subdict_0)
# {'key1': 1, 'otherkey': 0.256}

subdict_2 = ith_val_subdict(someDict, 2)
print(subdict_2)
# {'key1': 3, 'otherkey': 0.487}   

CodePudding user response:

You can use two zip in a list comprehension:

[dict(zip(someDict, vals)) for vals in zip(*someDict.values())]

output:

[{'key1': 1, 'otherkey': 0.256},
 {'key1': 2, 'otherkey': 0.221},
 {'key1': 3, 'otherkey': 0.487},
 {'key1': 4, 'otherkey': 0.454},
 {'key1': 5, 'otherkey': 0.555}]

NB. this will truncate the values to the length of the shortest sublist, if there is an uneven length and padding is needed, use itertools.zip_longest

  • Related