我一直想弄清楚如何排序这些字典:d1
和d2
里面的字典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
四次,我不知道是什么原因。
据我所知,可能有更有效的方法来做到这一点,所以任何信息都是值得欢迎的。
请解释你希望发生的事情(例如,你想看到什么输出),因为它不清楚你的问题。 – Amadan
这是非逻辑的代码,因为你可以做最后的循环,你会得到两个输出,我没有得到你的代码 –
你不应该有3个嵌套'for'循环都具有相同的循环变量(' k'和'v'),因为两个外部循环基本上只是让内部循环运行4次。请注意,仅仅执行'print(k,v)'就会打印出“v”作为整个字典未排序。 –