【发布时间】:2016-07-01 23:07:45
【问题描述】:
我有两个列表
a= ['and', 'people', 'them', 'become', 'treat', 'is', 'they', 'see', 'the', 'way', 'you', 'what']
b= [3, 6, 4, 6, 5, 2, 4, 3, 3, 3, 3, 4]
我需要一个字典,其中键是b 中的数字,值是a 中的单词。但是,键的值必须是唯一的。所以,输出是这样的:
c= {2 : 'is', 3 : ['and', 'see', 'the', 'way', 'you'], 4: ['them', 'they', 'what'], 5 : 'treat', 6 : 'become'}
我试过了:
mydict = {key:value for key, value in zip(b, a)}
print (mydict)
这是输出:
{2: 'is', 3: 'and', 4: 'them', 5: 'treat', 6: 'become'}
【问题讨论】:
-
总是使用列表作为值不是更好吗?然后你可以使用
mydict.setdefault(key, []).append(value)或collections.defaultdict(list)。否则你会遇到三种情况:键不存在,键存在字符串值,键存在列表值。 -
你需要什么输出?
-
我需要这个输出: c= {2 : 'is', 3 : ['and', 'see', 'the', 'way', 'you'], 4: ['他们','他们','什么'],5:'治疗',6:'成为'}
-
@DanielTiezzi,为什么不
5: ['treat']? -
因此,在分配给匹配键的值列表中具有相同长度的单词
标签: python dictionary