Home > database >  Data manipulation with Dictionaries in python
Data manipulation with Dictionaries in python

Time:08-31

I am working with dictionaries and want to solve this custom problem wherein I want values in my dictionary to be in the same position as in my_list. In case, we don't have the value in the dictionary it should place with '-'

  • All the values in the dictionary are available in my_list.
my_list = ['a', 'b', 'c', 'd']
d = {'x':['a', 'b', 'd'], 'y':['a', 'c'], 'z': ['d', 'b']}

expected output:

{'x':['a', 'b', '-', 'd'], 'y':['a', '-', 'c', '-'], 'z':['-', 'b', '-', 'd']}

CodePudding user response:

You can iterate over my_list and check each value exists in list that exist in d. We can change the dict in-place like below:

my_list = ['a', 'b', 'c', 'd']
d = {'x':['a', 'b', 'd'], 'y':['a', 'c'], 'z': ['d', 'b']}

for key, lst in d.items():
    d[key] = [val if val in lst else '-' for val in my_list]

print(d)
# {'x': ['a', 'b', '-', 'd'], 'y': ['a', '-', 'c', '-'], 'z': ['-', 'b', '-', 'd']}

CodePudding user response:

from collections import OrderedDict
my_list=['a','b','c','d']
d={'x':['a','b','d'],'y':['a','c'],'z':['d','b']}
z=list(d)
new=OrderedDict.fromkeys(z,'-')
for i in d.keys():
    dict = OrderedDict.fromkeys(my_list,'-')
    for j in d[i]:
        dict[j]=j
    new[i]=list(dict.values())
print(new)

  • Related