迭代字典列表

时间:2013-12-02 02:19:14

标签: python dictionary

我正在使用pyton 3.2 我有以下字典:

a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"],"number":["1","2","3"]}

我需要迭代这个字典列表,我想创建一个新的字典b,其中fruits中的值与颜色的值相同:

 b = {"fruits":["apple","grapes"],"colour":["apple", "grapes"],"number":["1","3"]}  

我认为这可行,但从此失去了:

b = {}
for item in a:
   if x in a[item]:

......不知道现在该怎么办?

如何在不使用itertools的情况下完成此操作? 除了我列出的字典之外,是否还有一个可用于任何字典的通用功能?

4 个答案:

答案 0 :(得分:0)

在这种情况下,您最好使用set

b = {"fruits": list(set(a['fruits']).intersection(a['colour'])}
b['colour'] = b['fruits']  # or maybe make a copy here...

答案 1 :(得分:0)

这样的东西?

a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"]}
b = {}

b['fruits'], b['colour'] = [], []

for fruit in a['fruits']:
    if fruit in a['colour']:
        b['fruits'].append(fruit)
        b['colour'].append(fruit)

答案 2 :(得分:0)

如果您不想在结果字典中使用数字,可以这样做......

<强>代码:

a = {"fruits":["apple","mangoes","grapes"],"colour":["apple","orange","grapes"],"number":["1","2","3"]}

b = dict()
b['fruits'] = b['colour'] = [x for x in a['fruits'] if x in a['colour']]

print b

<强>输出:

{'colour': ['apple', 'grapes'], 'fruits': ['apple', 'grapes']}

希望这会有所帮助:)

答案 3 :(得分:0)

b = {}
for fruit in a['fruits']:
    if fruit in a['colour']:
        b.setdefault('fruits', [])   # set if key is not present
        b.setdefault('colour', [])
        b.setdefault('number', [])
        b['fruits'].append(fruit)
        b['colour'].append(fruit)
        b['number'].append(a['number'][a['fruits'].index(fruit)])