I'm reeally sorry, being a noob in python is quite hard when you have project to do... Here is my problem
d= { 'a': [ '"123728"', '"102359"', '"110663"', '"110664"','"110665"', '"110666"', '"110667"', '"110668"', '"110669"', '"110670"', '"110671"', '"110672"', '"115663"', '"115664"', '"115665"', '"122330"', '"122351"', '"110673"', '"120433"', '"121831"'],
'b': ['"100016"', '"101424"', '"101948"', '"102832"', '"108834"', '"110397"', '"110622"', '"110679"', '"110680"', '"110681"', '"110682"', '"116693"', '"123331"', '"102359"', '"110683"', '"115666"', '"115667"', '"124098"', '"125243"', '"140965"', '"121002"']}
The value from the dict d are the keys from d1
d1= {'"110674"': '"Apple"', '"110682"': "Banana", '"123331"': "Melon", '"110397"': "Orange"} # correspondance
What I want is to replace the value from d to it correspondance in d1 and delete the one that do not correspond
d3= { 'a': "", 'b': ["Banana", "Melon", "Orange"]}
Here is my code
for key, value in d.items():
for key2, value2 in d1.items():
for elem in value:
print(key2)
if elem == key2:
full_dict[key] = value2
pprint.pprint(full_dict)
But I have this result
defaultdict(None, {'b': 'Orange'})
Thank you very much
CodePudding user response:
You can iterate d
dictionary, then for each keys, iterate the dictionary d1
and check if the key of the second dictionary exists in the value of the first dictionary, then add it to the result dictionary at last.
result = {}
for k,v in d.items():
temp = []
for key,val in d1.items():
if key in v:
temp.append(val)
result[k] = temp if temp else ''
result
{'a': '', 'b': ['Banana', 'Melon', 'Orange']}
PS: The expected output you have doesn't match for the given data, Apple
should not have been there.
CodePudding user response:
Use the following dict comprehension:
d3 = { key : [d1[v] for v in value if v in d1] for key, value in d.items() }
print(d3)
Output
{'a': [], 'b': ['Orange', 'Banana', 'Melon']}
The above is equivalent to the below for-loop:
d3 = {}
for key, value in d.items():
d3[key] = [d1[v] for v in value if v in d1]
If you want to match the exact output (i.e an empty string in place of an empty list), use:
d3 = {}
for key, value in d.items():
res = [d1[v] for v in value if v in d1]
d3[key] = res if res else ""
print(d3)
Output
{'a': '', 'b': ['Orange', 'Banana', 'Melon']}