打印带有列表值的常规字典

时间:2018-12-21 13:43:34

标签: python python-2.7

我有一本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'])])

能请你帮忙吗?

4 个答案:

答案 0 :(得分:2)

这是一种实现方法:

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

for i, name in enumerate(my_d['Names']):
    print("{} is {} and from {}".format(name, my_d['Ages'][i], 
          my_d['Cities'][i]))

不过,我觉得您的数据结构对于此信息不正确。有了更多的上下文,我们也许可以提出更好的建议。问题本身不是字典排序,因为“标题”(字典键)的排序无关紧要;数据的顺序 保留在针对键存储的列表中。

答案 1 :(得分:1)

如果您知道字典中具有这些特定键,则可以使用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.

答案 2 :(得分:1)

对于您的示例,要打印的信息存储在按排序的列表中,因此您可以使用zip()正常打印它们:

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

for name, age, city in zip(my_d['Names'], my_d['Ages'], my_d['Cities']):
     print('%s is %s from %s' % (name, age, city))

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

但是,如果您仅将数据存储在嵌套字典中,例如:

my_d = {
    "Kate": {"age": 21, "city": "New York"},
    "Clair": {"age": 31, "city": "Amsterdam"},
    "Jack": {"age": 38, "city": "Oslo"},
}

您将需要在这里关注顺序,因为只有 unordered 字典存在。您需要按照各自的年龄对字典items()进行排序,然后应用collections.OrderedDict()

from collections import OrderedDict

sorted_by_age = OrderedDict(sorted(my_d.items(), key=lambda x: x[1]["age"]))
for name, info in sorted_by_age.items():
    print("%s is %s from %s" % (name, info["age"], info["city"]))

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

注意:如果您升级到 Python 3.6 + ,则可以避免担心字典顺序,因为会保持插入顺序。

答案 3 :(得分:0)

直接使用pandas。只需按照以下步骤遍历DataFrame的行

import pandas as pd

my_d = {'Names':['Kate','Clair','Jack'],'Ages':['21','31','38'],'Cities':['New York','Amsterdam','Oslo']}
df = pd.DataFrame(my_d)
for i, row in df.iterrows():
  s = row['Names'] + ' is ' + row ['Ages'] + ' from ' + row['Cities'] + '.'
  print(s)

输出

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