如何用Python中的2个词典创建一个dict?

时间:2012-08-21 11:55:28

标签: python dictionary

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

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

3 个答案:

答案 0 :(得分:5)

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

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

您可以使用dict comprehension获取一个带有类别名称作为键的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键,将内部理解设置为值。

答案 1 :(得分: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'])}

答案 2 :(得分:1)

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

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)