5

我现在正在处理 Python 字典。我写了一段代码:

import random

categories = {1 : "Antics", 2 : "Tickets", 3: "Moviez",
              4 : "Music", 5 : "Photography", 6 : "Gamez", 7 : "Bookz",
              8 : "Jewelry", 9 : "Computers", 10 : "Clothes"}

items = {"Picture" : 1, "Clock" : 1, "Ticket for Mettalica concert" : 2,
         "Ticket for Iron Maiden concert" : 2, "Ticket for Placebo concert" : 2,
         "The pianist" : 3, "Batman" : 3, "Spider-Man" : 3,
         "WoW" : 6, "Cabal" : 6, "Diablo 3" : 6, "Diablo 2" : 6,
         "Thinking in Java" : 7, "Thinking in C++" : 7, "Golden ring" : 8,
         "Asus" : 10, "HP" : 10, "Shoes" : 11}

for key, val in categories :
    for k, v in items :
        if key == v :
            print(val, k)

我想创建一个第三个字典,在那里我会喜欢:

dictThe3rd = {"Antics" : "Picture", "Antics" : "Clock", "Tickets" : "Ticket for Mettalica concert", "Ticket" : "Ticket for Iron Maiden concert", "Ticket" : "Ticket for Placebo concert", ...} 

等等。

这该怎么做?我的代码显示:

test.py, line 14, in <module>
    for key, val in categories :
TypeError: 'int' object is not iterable
4

3 回答 3

6

如果你使用 dict 作为迭代器,它只会产生它的键,而不是键和值的元组。您必须使用categories.items()(或者categories.iteritems()如果您只使用 Python 2.x)来获取这些元组:

for key, val in categories.items() :
    for k, v in items.items() :
        if key == v :
            print(val, k)

您可以使用 dict 理解来获取一个以类别名称为键、该类别中的所有项目作为值的 dict:

>>> dict3 = { catname : [ item for item, itemcat in items.items() if itemcat == cat  ] for cat, catname in categories.items()  }
>>> dict3
{'Antics': ['Picture', 'Clock'],
'Bookz': ['Thinking in C++', 'Thinking in Java'],
'Clothes': ['Asus', 'HP'],
'Computers': [],
'Gamez': ['Diablo 3', 'Diablo 2', 'Cabal', 'WoW'],
'Jewelry': ['Golden ring'],
'Moviez': ['The pianist', 'Batman', 'Spider-Man'],
'Music': [],
'Photography': [],
'Tickets': ['Ticket for Mettalica concert',
'Ticket for Placebo concert',
'Ticket for Iron Maiden concert']}

解释:

方括号中的内部理解将列出所有类别为cat. 外部理解将遍历所有类别键和名称,将类别名称设置为新的 dict 键,将内部理解设置为值。

于 2012-08-21T12:01:07.293 回答
2

将您的代码更改为:

for key, val in categories.iteritems():
    for k, v in items.iteritems():
        if key == v:
            print(val, k)

通过这种方式,您可以使用 itemiterator 迭代键/值对,这会产生比items()大型字典更好的性能。

你想要的可能是这样的:

import collections
dictThe3rd=collections.defaultdict(set)
for key, val in categories.iteritems():
    for k, v in items.iteritems():
        if key == v:
            dictThe3rd[val].add(k)
print dictThe3rd

产生

{'Tickets': set(['Ticket for Mettalica concert', 'Ticket for Placebo concert',
    'Ticket for Iron Maiden concert']),
'Jewelry': set(['Golden ring']),
'Antics': set(['Picture', 'Clock']),
'Moviez': set(['Batman', 'Spider-Man', 'The pianist']),
'Bookz': set(['Thinking in Java', 'Thinking in C++']),
'Gamez': set(['Diablo 3', 'Diablo 2', 'WoW', 'Cabal']),
'Clothes': set(['Asus', 'HP'])}
于 2012-08-21T12:01:40.073 回答
1

您应该items()在 Stefan 解决方案中使用 as ,但如果您想构建新字典而不是打印创建列表或附加到它:

dictThe3rd = {}
for key, val in categories.items():
    for k, v in items.items():
        if key == v :
            #print(val, k)
            try:
                dictThe3rd[val].append(k)
            except KeyError:
                dictThe3rd[val] = [k]

print(dictThe3rd)
于 2012-08-21T12:07:20.173 回答