Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典输出问题_Python_Python 2.7_Dictionary_Output - Fatal编程技术网

Python 字典输出问题

Python 字典输出问题,python,python-2.7,dictionary,output,Python,Python 2.7,Dictionary,Output,我试图更好地理解下面的代码,了解为什么会出现某些输出 stuff = {'purple':[0, 106, 506, 'SI', 'Lauren'], 'blue':'Cornflower', 'yo':'green'} stuff_keys_sorted = sorted(stuff.keys()) print sorted(stuff.keys()) for k in stuff_keys_sorted: if type(stuff[k]) == type(['hello', 'go

我试图更好地理解下面的代码,了解为什么会出现某些输出

stuff = {'purple':[0, 106, 506, 'SI', 'Lauren'], 'blue':'Cornflower', 'yo':'green'}
stuff_keys_sorted = sorted(stuff.keys())
print sorted(stuff.keys())
for k in stuff_keys_sorted:
    if type(stuff[k]) == type(['hello', 'goodbye']):
        for item in stuff[k]:
            print item
print k
电流输出为:

0
106
506
SI
Lauren
yo

我明白为什么直到“哟”的最后一行,一切都在发生。为什么“yo”是打印的唯一选项,我的代码不应该只打印字典中的任何键吗

printk
语句置于循环之外。Python到达该语句时,的
循环就完成了,然后只打印
k
的最后一个值

如果要打印每个键,需要使其成为循环的一部分:

for k in stuff_keys_sorted:
    # ...
    print k
关于代码的其他一些注释:

  • 您不必调用
    .keys()
    stuff\u keys\u sorted=sorted(stuff)
    就足以获得字典键的排序序列
  • 要测试特定类型,请使用
    isinstance()
    而不是使用
    type(..)=type(..)

    即使您确实需要使用
    type()
    ,也不需要包含内容的列表<代码>类型([])
就足够了。但是使用
type(..)is list
(因为
type([])
的结果是be
list
,并且每个Python内置类型只有一个副本,所以使用
is
将是一个更快的测试)


您正在使用
print k
打印最后一个键,因为它不是循环的一部分。您需要将其缩进以成为循环的一部分。旁注:无论您在列表中输入了什么
类型(['hello','debye'])
,您将始终使用
列表作为类型。在这种情况下,您实际上想验证什么是
if type(stuff[k])==type(['hello','debye']):
应该做什么?非常感谢您的解释,它只会打印“yo”,因为它在for循环之外!还感谢您提供关于使用if-isinstance(stuff[k],list)的提示:这比只使用type更有效。
if isinstance(stuff[k], list):