Printing from two dictionaries

373 views Asked by At
states = {state, abbr}
cities = {abbr, capital}

I'd like to print out state, abbr, capital or some other order of the 3 values. I tried inverting the key, value pair in states with:

inv_states = {state: abbr for abbr, state in states.items()}
for abbr, capital in sorted(inv_states.items()):
         print(abbr, ':', capital)

Now I've got:

states = {abbr, state}
cities = {abbr, capital}

And then trying to create a new dict with (I don't fully understand the below code):

newDict = defaultdict(dict)
for abbr in (inv_states, cities):
         for elem in abbr:
                 newDict[elem['index']].update(elem)
fullDict = newDict.values()
print(fullDict)

But I'm getting a string indices must be intergers error.

Little help please. Or am I completely on the wrong path? Thanks.

1

There are 1 answers

1
dm03514 On

Assuming your data is in dictionaries, (which it is not in your example code). It should be pretty straightforward to pring out the data you are looking for

for state, abbr in states.items():
   print('{0}, {1}, {2}'.format(state, abbr, cities[abbr]))