用列表顺序打印dictornary

时间:2015-05-30 06:36:55

标签: python list dictionary printing format

我有以下代码,它是地址簿(词典列表)和列表。我们的想法是按照列表的顺序打印字典中的项目(因为dicts搞乱了所有内容的顺序)。当我运行此代码时,它会抛出异常(如下所示)。我不知道自己做错了什么,因为我尝试了很多不同的变化,我不断回过头来想知道它为什么不起作用。

请帮帮忙?

addressBook = [
    {
    'Nickname': 'Jimmy',
    'Name': 'James Roberts',
    'Address': '2/50 Robe Street',
    'Phone': '0273503342'
    },
    {
    'Nickname': 'Bob',
    'Name': 'Robert',
    'Address': '1 Vivan Street',
    'Phone': '067578930'
    }
]

addressFields = ['Nickname', 'Name', 'Address', 'Phone']

def listAll(addressBook, addressFields):
    for i in addressBook:
        for key in addressFields:
            print("{0} {1}".format(key, addressBook[i][key]))

    print("{0} {1}".format(key, addressBook[i][key]))


TypeError: list indices must be integers, not dict

4 个答案:

答案 0 :(得分:2)

首先,在'之后,您在addressBook字面值中遗漏了'James Roberts。其次,问题是您正在执行addressBook[i][key]而不是i[key]i已经引用了addressBook中包含的字典,因此您的代码尝试使用list的元素作为自身的索引。

def listAll(addressBook, addressFields):
    for i in addressBook:
        for key in addressFields:
            print('{} {}'.format(key, i[key]))

Python 3友好的单行:

def listAll(addressBook, addressFields):
    print(*('{} {}'.format(j, i[j]) for i in addressBook for j in addressFields), sep='\n')

答案 1 :(得分:1)

或者在一行中:

print('\n'.join(element for element in [j+" "+ i[j] for i in addressBook for j in addressFields]
))

答案 2 :(得分:0)

#!/usr/bin/python

addressBook = [{'Nickname': 'Jimmy', 'Name': 'James Roberts', 'Address': '2/50 Robe Street', 'Phone': '0273503342'},{'Nickname': 'Bob', 'Name': 'Robert', 'Address': '1 Vivan Street', 'Phone': '067578930'}]

addressFields = ['Nickname', 'Name', 'Address', 'Phone']

def listAll(addressBook, addressFields):
  for i in addressBook:
    for val in addressFields:
      print("{0} {1}".format(val, i[val]))

listAll(addressBook, addressFields)

答案 3 :(得分:-1)

发布此问题后,我找到了答案。

我将addressBook for循环转换为范围(len(addressBook))并且它有效。

for i in range(len(addressBook)):