TypeError迭代字典中的项目

时间:2017-08-02 23:28:11

标签: python dictionary python-3.6 counting

我有一个词典列表,其中每个词典还包含一个项目列表(爱好)。

我只想补充每个爱好中有多少个,并将结果放入新词典中。

我的结果应如下:{'Python': '3', 'cooking': '4', 'reading': '3', ... }

这个爱好接着是它存在的总次数。

这是我的代码:

people = [{'name': 'John', 'age': 47, 'hobbies': ['Python', 'cooking', 'reading']},
          {'name': 'Mary', 'age': 16, 'hobbies': ['horses', 'cooking', 'art']},
          {'name': 'Bob', 'age': 14, 'hobbies': ['Python', 'piano', 'cooking']},
          {'name': 'Sally', 'age': 11, 'hobbies': ['biking', 'cooking']},
          {'name': 'Mark', 'age': 54, 'hobbies': ['hiking', 'camping', 'Python', 'chess']},
          {'name': 'Alisa', 'age': 52, 'hobbies': ['camping', 'reading']},
          {'name': 'Megan', 'age': 21, 'hobbies': ['lizards', 'reading']},
          {'name': 'Amanda', 'age': 19, 'hobbies': ['turtles']},
          ]


data = {}
for d in people:
    for hobby in people['hobbies']:
        if hobby not in data:
            data[hobby] = int(1)
        else:
            data[hobby].append(int(1))

for key, value in data.items():
    print(key + ':', end=' ')
    sumvalues = 0
    for elem in value:
        sumvalues += elem
    print(sumvalues)

当我跑步时,我得到:

TypeError: list indices must be integers or slices, not str

不确定是什么导致错误。

2 个答案:

答案 0 :(得分:0)

在线......

for hobby in people['hobbies']:

您将字符串'hobbies'作为索引传递到列表people。也许你打算这样做......

for hobby in d['hobbies']:

答案 1 :(得分:0)

您的代码中存在两个问题:

  • 您可能希望从'hobbies'而不是d(这是一个列表)获取people
  • 如果您的data中没有条目,但是请尝试附加条目,则不会添加列表。

修复它们看起来像这样:

people = [{'name': 'John', 'age': 47, 'hobbies': ['Python', 'cooking', 'reading']},
          {'name': 'Mary', 'age': 16, 'hobbies': ['horses', 'cooking', 'art']},
          {'name': 'Bob', 'age': 14, 'hobbies': ['Python', 'piano', 'cooking']},
          {'name': 'Sally', 'age': 11, 'hobbies': ['biking', 'cooking']},
          {'name': 'Mark', 'age': 54, 'hobbies': ['hiking', 'camping', 'Python', 'chess']},
          {'name': 'Alisa', 'age': 52, 'hobbies': ['camping', 'reading']},
          {'name': 'Megan', 'age': 21, 'hobbies': ['lizards', 'reading']},
          {'name': 'Amanda', 'age': 19, 'hobbies': ['turtles']},
          ]

data = {}
for d in people:
    for hobby in d['hobbies']:
        if hobby not in data:
            data[hobby] = [1]
        else:
            data[hobby].append(1)

for key, value in data.items():
    print(key + ':', end=' ')
    sumvalues = 0
    for elem in value:
        sumvalues += elem
    print(sumvalues)

然而,collections.Counter已经涵盖(以更高效的方式)某些内容的代码很多:

from collections import Counter
cnts = Counter(hobby for d in people for hobby in d['hobbies'])
for hobby, cnt in cnts.items():
    print('{}: {}'.format(hobby, cnt))

打印:

Python: 3
cooking: 4
reading: 3
horses: 1
art: 1
piano: 1
biking: 1
hiking: 1
camping: 2
chess: 1
lizards: 1
turtles: 1

您还可以使用计数器的most_common方法按降序排序:

for hobby, cnt in Counter(hobby for d in people for hobby in d['hobbies']).most_common():
    print('{}: {}'.format(hobby, cnt))