在第一个 for 循环之后,我的字典缩小了,我在 for 循环的末尾只剩下一个键值对,如结果所示。最后以某种方式给出了字符串错误。谁能建议我对字典有什么不了解?
states = {
'Bagmati' : 'BG',
'Gandaki' : 'GD',
'Karnali' : 'KL',
'Janakpur' : "JK",
'Mechi' : 'MC'
}
cities = {
'BG' : 'Kathmandu',
"GD" : "Pokhara",
"KL" : "Jumla",
"MC" : 'Jhapa'
}
cities['BG'] = 'Hetauda'
cities['MC'] = 'Taplejung'
cities['BG'] = 'Ramechap'
cities['JK'] = 'Dhanusha'
print(f'1. {states}')
for states, abbrev in list(states.items()):
print(f'the {states} is abbreviated as {abbrev}')
print(states)
print(cities)
#print every city and states
for abbrev, cities in list(cities.items()):
print(f'the {abbrev} state has {cities} city')
print(f'2. {states}')
print(f'3. {cities}')
# now lets access both the states and cities dictionaries
for states, abbrev in list(state`enter code here`s.items()):
print(f' the {states} state is abbreviated as {abbrev}')
print(f' and has the city {cities[abbrev]}')
结果:
C:\Users\Prabin\Desktop\Desktop\personal-projects\mystuff\39. Dictionaries>python new12.py
1. {'Bagmati': 'BG', 'Gandaki': 'GD', 'Karnali': 'KL', 'Janakpur': 'JK', 'Mechi': 'MC'}
the Bagmati is abbreviated as BG
the Gandaki is abbreviated as GD
the Karnali is abbreviated as KL
the Janakpur is abbreviated as JK
the Mechi is abbreviated as MC
Mechi
{'BG': 'Ramechap', 'GD': 'Pokhara', 'KL': 'Jumla', 'MC': 'Taplejung', 'JK': 'Dhanusha'}
the BG state has Ramechap city
the GD state has Pokhara city
the KL state has Jumla city
the MC state has Taplejung city
the JK state has Dhanusha city
2. Mechi
3. Dhanusha
Traceback (most recent call last):
File "new12.py", line 36, in <module>
for states, abbrev in list(states.items()):
AttributeError: 'str' object has no attribute 'items'