简体   繁体   中英

Dictionaries and For Loops

say that the following is our code:

d = {"Happy":"Clam", "Sad":"Panda"}
for i in d:
    print(i)

now print(i ) will print out just the keys, but how could I change it so that it printed the values?

d = {"Happy":"Clam", "Sad":"Panda"}
for i in d:
    print(i, d[i]) # This will print the key, then the value

or

d = {"Happy":"Clam", "Sad":"Panda"}
for k,v in d.items(): # A method that lets you access the key and value
    print(k,v) # k being the key, v being the value
d = {"Happy":"Clam", "Sad":"Panda"}
for i in d:
        print(i, d[i])

Gives me:

('Sad', 'Panda')
('Happy', 'Clam')

A Python dict has a number of methods available for getting a list of the keys, values, or both.

To answer your question, you can use d.values() to get a list of the values only:

d = {"Happy":"Clam", "Sad":"Panda"}
for v in d.values():
   print(v)

Output:

Clam
Panda

The items() method is particularly useful, though, so should be mentioned.

d = {"Happy":"Clam", "Sad":"Panda"}
for k, v in d.items():
   print(k, v)

will print:

Happy Clam
Sad Panda

A warning about the ordering of items from the documentation:

CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions.

A simple approach would to use a for each loop

for value in d.values:
    print(value)

You could also make a generator. Generators are iterable sequences that you can stop and resume.

def generator(input):
    for value in input.values():
        yield value

gen = generator(d);
print(d.next()) // Clam

// Doing complex calculations
answer = 21 + 21

print(d.next()) // Panda

Another way is using the higher order function 'map'.

map( print, d.values() )

// You can also use generators ;)
map( print, gen )

Lastly, in python 3 dictionaries now support compression. Dictionary compression is great for creating dictionaries, not so much for printing the content of each entry's value. It's something worth googling, since everything in python is a dictionary.

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