简体   繁体   中英

In a python dictionary how can I display the content of the key and value of the dictionary entry?

city = {"New York": 2, "Minnespolis": 2, 'thing ' : 3}
print(city)
for key in city:
    print(city)

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

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM