Reputation: 83
I have the following dictionaries:
d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}
d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]
I would like the following output:
d1 = {"00f_5" :["AAA","AAC",3], "00f_6": ["CCC",2,3]}
I have tried multiple attempts, but I couldn't get it. Any help would be much appreciated.
Upvotes: 1
Views: 87
Reputation: 44505
I would not suggest overwriting the first dict. Just make a new one (d3
).
Given
d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}
lst = [
{"marker":"00f_5",1: 'AAA'},
{"marker":"00f_6", 1: 'CCC'},
{"marker":"00f_5", 2:"AAC"}
]
Code
d3 = {}
for d in lst:
key = d["marker"]
value = d1[key]
for k, v in d.items():
if not isinstance(k, int): # skip to numeric keys
continue
if key not in d3: # fill missing entries
d3[key] = value
idx = k - 1
d3[key][idx] = v # overwrite list item
d3
{'00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]}
Upvotes: 0
Reputation: 106553
You can build a dict that maps the marker to a sub-dict that maps numeric keys to the 3-letter codes, so that given a marker and a numeric key, you can use dict.get
method to get the mapped code if it exists:
d = {}
for s in d2:
d.setdefault(s['marker'], {}).update(s)
d1 = {k: [d[k].get(i, i) for i in l] for k, l in d1.items()}
so that given:
d1 = {"00f_5" :[1,2,3], "00f_6": [1,2,3]}
d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]
d1
will become:
{'00f_5': ['AAA', 'AAC', 3], '00f_6': ['CCC', 2, 3]}
Upvotes: 3
Reputation: 296
Although I will not give you the full program, you might try to understand and play with the following code:
d2 = [{"marker":"00f_5",1: 'AAA'},{"marker":"00f_6", 1: 'CCC'},{"marker":"00f_5", 2:"AAC"}]
for d in d2:
for key, value in d.items():
if key == "marker":
marker = value
else:
reference = value
content = key
print("Marker: {}, Reference: {}, Content: {}".format(marker, reference, content))
Upvotes: 0