Data manipulation with Dictionaries in python

Question:

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']}
Asked By: JamesHunt

||

Answers:

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']}
Answered By: I'mahdi
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)

Answered By: Jemesh Khatik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.