简体   繁体   中英

printing Dictionary using "for" loop

states = { 'Orengon': 'OR' 'Florida': 'FL' 'California': 'CA' 'New York': 'NY' 'Michigan': 'MI' }

for state, abbrev in list(states.items()):

   print(f"{state} is abbreviated {abbrev}")

Here in "for" loop why are we using "list" keyword?

and what is .items keyword for(states.items)?

list(states.items())

It will convert it into list. However, it is not needed as states.items() returns list on tuples.

Dictionary

states = { 'Orengon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI', }

After performing states.items()

[('Orengon', 'OR'), ('Michigan', 'MI'), ('New York', 'NY'), ('Florida', 'FL'), ('California', 'CA')]

After performing list(states.items())

[('Orengon', 'OR'), ('Michigan', 'MI'), ('New York', 'NY'), ('Florida', 'FL'), ('California', 'CA')]

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