0
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.

4

1 に答える 1

3

データが辞書にあると仮定します(サンプルコードにはありません)。探しているデータを突き出すのは非常に簡単なはずです

for state, abbr in states.items():
   print('{0}, {1}, {2}'.format(state, abbr, cities[abbr]))
于 2012-10-26T17:50:06.980 に答える