我有一本my_d词典,您在下面看到:

my_d={'Names':['Kate','Clair','Jack'],'Ages':['21','31','38'],'Cities':['New York','Amsterdam','Oslo']}


我想要这样的输出:

Kate  is  21 from  New York.
Clair is  31 from  Amsterdam.
Jack  is  38 from  Oslo.


我注意到常规字典中没有顺序的问题。这对我来说不是一个好的解决方案,因为顺序再次更改。我试图按值或键排序:

for key, value in sorted(l.items(), key=lambda (k,v): (v,k)):
    print "%s: %s" % (key, value)


仍然不是我想要的那个。
我什至通过键和值使用了订单collections.OrderedDict()

print collections.OrderedDict(sorted(l.items(), key=lambda x:x[1]))


但如您所见,输出顺序不正确:

OrderedDict([('Ages', ['21', '31', '38']), ('Cities', ['New York', 'Amsterdam', 'Oslo']), ('Names', ['Kate', 'Clair', 'Jack'])])


能否请你帮忙?

最佳答案

如果您知道字典具有这些特定键,则可以使用zip(),如下所示:

for l in zip(my_d['Names'], my_d['Ages'], my_d['Cities']):
    print("{:5s} is  {} from  {}.".format(*l))


出:

Kate  is  21 from  New York.
Clair is  31 from  Amsterdam.
Jack  is  38 from  Oslo.

关于python - 打印带有列表值的常规词典,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53885808/

10-13 02:53