我有一个字典,键是整数值,值是字符串列表。 我想反过来说,字符串成为键,整数成为值。 像:
首先设计:
{1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
第二个设计:
{"a": [1,2,3,6], "b":[2,4], "cd":[4,6]}
任何线索?感谢
答案 0 :(得分:2)
对于单行的爱(注意:效率很低!):
d2 = {val: [key for key in d if val in d[key]] for lst in d.itervalues() for val in lst}
答案 1 :(得分:2)
一种简单的方法是创建一个defaultdict
,为新键提供一个空列表,然后为当前dict中的每个列表创建一个键,并将原始的dict键附加到新的列表:
from collections import defaultdict
orig = {1: ['a'], 2: ['a', 'b'], 3: ['a'], 4: ['b', 'cd'], 6: ['a', 'cd']}
d = defaultdict(list)
for k, v in orig.items():
for string in v:
d[string].append(k)
# d = {'a': [1, 2, 3, 6], 'b': [2, 4], 'cd': [4, 6]}
答案 2 :(得分:2)
代码
first_map = {1: ["a"], 2: ["a", "b"], 3: ["a"], 4: ["b", "cd"], 6: ["a", "cd"]}
second_map = {}
for key, value in first_map.items():
for i in value:
if i in second_map:
second_map[i].append(key)
else:
second_map[i] = [key]
print(second_map)
答案 3 :(得分:1)
z = {1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
d = dict()
for k, v in z.iteritems():
for i in v:
if i in d:
d[i].append(k)
else:
d[i] = [k]
使用iteritems()
而非items()
更好一点,因为前者在Python 2中创建了一个生成器。
答案 4 :(得分:1)
dict1= {1:["a"], 2:["a","b"], 3:["a"], 4:["b", "cd"], 6:["a","cd"]}
dict2= {}
for key, value in dict1.items():
for val in value:
if val in dict2:
dict2[val].append(key)
dict2[val]= list(set(dict2[val]))
else:
dict2[val]= [key]
答案 5 :(得分:1)
<html>
<head>
</head>
<body>
<h1>heading</h1>
</body>
</html>