I have 2 dictionaries:
fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}
The end result I want is:
inv3 = {'apple': 45, 'banana': 1, 'cherry': 1, 'peach': 1}
I have tried this sample code so far because this output looks almost similar to what I want except it is not printing out the way I want but close:
d1 = {'apple': 3, 'orange': 1,}
d2 = {'apple': 42, 'orange': 1}
ds = [d1, d2]
d = {}
for k in d1.keys():
d[k] = tuple(d[k] for d in ds)
print(ds)
The output would be this way:
[{'apple': 3, 'orange': 1}, {'apple': 42, 'orange': 1}]
When I tried to enter my 2 dictionaries using the sample code:
fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}
fruit3 = [fruit1, fruit2]
d = {}
for k in fruit1.keys():
d[k] = tuple(d[k] for d in fruit3)
print(fruit3)
I get this error message:
Traceback (most recent call last):
line 8, in <module>
d[k] = tuple(d[k] for d in ds)
line 8, in <genexpr>
d[k] = tuple(d[k] for d in ds)
KeyError: 'banana'
My questions are:
- How do I get the output I intended without importing any module? I am only in Chapter 5: Dictionaries and Data Structures in Automating The Boring Stuff
- Why did the KeyError: 'banana' occur?
Thanks!