Skip to main content
 首页 » 编程设计

python之Python 词典帮助

2025年05月04日12lhb25

我有一个字典,我想遍历键,测试键,然后打印通过测试的键。

例如,目前我的代码如下所示:

x = {4:"a", 1:"b", 0:"c", 9:"d"} 
for t in x: 
    if t > 2: 
        print t 

然而,所有的输出只是关键。

如何让代码打印出代码末尾的值,而不是键?

此外,如何以字典的形式获取它,{key : value}?

请您参考如下方法:

你可以试试这个:print t, x[t]

或者这个:

for key, val in x.items(): 
    if key > 2: 
        print key, val 

如果您只想将要打印的对放入新字典中,则必须将它们放在那里:

newdict = {} 
for key, val in x.items(): 
    if key > 2: 
        print key, val 
        # put all the keys > 2 into the new dict 
        newdict[key] = val 

当然,该解决方案在插入时正在打印。如果你做的不仅仅是一个小脚本,你会从打破功能中获得更多的实用性,确保任何给定的函数只做一件事情:

def filter_dict(x): 
    newdict = {} 
    for key, val in x.items(): 
        if key > 2: 
            # put all the keys > 2 into the new dict 
            newdict[key] = val 
 
def pretty_print(dct): 
    for k, v in dct.items(): 
        print k, v 
 
filtered = filter_dict(x) 
 
pretty_print(dct) 

当然,如果你只是调试,这并不适用,并且有一些方法取决于你正在编写的程序有多大:如果你做的事情足够简单,那么额外的灵 active 你通过分解功能得到的结果会丢失,因为需要额外的努力来弄清楚任何给定的东西到底做了什么。也就是说:您通常应该这样做。

此外,在 Python 中通过简单比较过滤列表的最惯用方法是使用 dict comprehension (Python 2.7/3.0 中的新功能):

filtered = {key: val for key, val in x if key > 2}