0

Before claiming this question is a duplicate

I found a similar question posted here. I think it's because I'm using python3, but I received TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items' and AttributeError: 'dict' object has no attribute 'iterkeys' for various solutions proposed.

Question

I have two dictionaries with identical keys. I would like to merge them into a single dictionary in which the keys remain the same but the values are combined.

As an example, I have some sample gradebook data. I would like to place the dictionary key-value pairs as labels in a legend.

dict_one = {'average' : 84, 'median' : 86.5, 'stdev' : 3.35}
dict_two = {'average' : 'B', 'median' : 'B+', 'stdev' : 'F'}

How can I modify the dictionaries to get back

dict_res = {'average' : (84, 'B'), 'median' : (86.5, 'B+'), 'stdev' : (3.35, 'F')}

I think a tuple (example: (84, 'B')) would be best, but a list (example: [84, 'B']) can work too.

1 Answers1

0

Try:

dict_one = {'average' : 84, 'median' : 86.5, 'stdev' : 3.35}
dict_two = {'average' : 'B', 'median' : 'B+', 'stdev' : 'F'}
ds = [dict_one, dict_two]
d = {}
for k in dict_one.keys():
    d[k] = tuple(d[k] for d in ds)

print(d)
Murtuza Z
  • 5,639
  • 1
  • 28
  • 52