【发布时间】:2016-07-26 00:50:32
【问题描述】:
我一直在试图弄清楚如何对这些字典进行排序:d1 和 d2inside 字典 d3。
d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
for k,v in sorted(d3['breakfast'].items()):
for k,v in sorted(d3.items()):
print(k,v)
这是输出:
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
它正确排序了两个breakfast和dessert,然后在dessert、'cream'和'eggs'里面的顺序是错误的。
应该是:
dessert {'cake':1, 'cream':1}
它还会打印“排序”字典d3 四次,我不确定为什么。
据我所知,可能有更有效的方法可以做到这一点,因此欢迎提供任何信息。
【问题讨论】:
-
请解释您希望发生什么(例如您希望看到什么输出),因为您的问题并不清楚。
-
这是不合逻辑的代码,因为你可以只做最后一个 for 循环,你会得到两个输出,我没有得到你的代码
-
你不应该有 3 个嵌套的
for循环,它们都具有相同的循环变量(k和v),因为两个外部循环基本上只是让内部循环运行 4 倍。请注意,仅执行print(k,v)正在打印出v是整个字典未排序。 -
仍在尝试获取挂起循环,我并没有真正想要的格式,我只是希望对它们进行排序和打印。我有点想我有一对多的循环,但我尝试的每一个变化都不起作用。我的意思是,不到一个小时前,我什至不明白 k 和 v 代表什么。
标签: python sorting python-3.x dictionary