city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
print(city)
for key in city:
print(city)
Asked
Active
Viewed 44 times
-1

BoarGules
- 16,440
- 2
- 27
- 44
-
2`for key, value in city.items(): print(key, value)` – PacketLoss May 10 '21 at 03:26
-
1It is a dictionary, not a directory. What do you want that `print(city)` doesn't do? – Tim Roberts May 10 '21 at 03:28
-
3Does this answer your question? [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – Xiddoc May 10 '21 at 03:31
2 Answers
2
Below I provide you with two option. Also this iterable is called a dictionary not a directory, although this can be a typo, I'd like to point that out.
Option1
You can use dict.items()
city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
for k,v in city.items():
print(f'key: {k}')
print(f'value: {v}')
Option two use dict[key]
city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
for k in city:
print(f'key: {k}')
print(f'value: {city[k]}')
output
key: New York
value: 2
key: Minnespolis
value: 2
key: thing
value: 3

Buddy Bob
- 5,829
- 1
- 13
- 44
0
Do you mean to access the value by key?
city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
print(city)
for key in city:
print(city[key])

HW Siew
- 973
- 8
- 16