简体   繁体   English

字典和循环

[英]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? 现在print(i )仅会打印出键,但是如何更改它以打印出值呢?

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. Python dict有许多可用于获取键,值或两者的列表的方法。

To answer your question, you can use d.values() to get a list of the values only: 要回答您的问题,可以使用d.values()列表:

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. 但是, items()方法特别有用,因此应予以提及。

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. CPython实现细节:键和值以任意顺序列出,该顺序是非随机的,在Python实现中会有所不同,并且取决于字典的插入和删除历史。

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”。

map( print, d.values() )

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

Lastly, in python 3 dictionaries now support compression. 最后,在python 3中,字典现在支持压缩。 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. 值得一试,因为python中的所有内容都是字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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