converting a dictionary to another one
本问题已经有最佳答案,请猛点这里访问。
我有一个字典,键是整数值,值是字符串列表。我想让它反过来,字符串变成键,整数变成值。像:
第一个设计:
1 | {1:["a"], 2:["a","b"], 3:["a"], 4:["b","cd"], 6:["a","cd"]} |
第二种设计:
1 | {"a": [1,2,3,6],"b":[2,4],"cd":[4,6]} |
有什么线索吗?谢谢
代码
1 2 3 4 5 6 7 8 9 | 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) |
一个简单的方法是创建一个为新键提供空列表的
1 2 3 4 5 6 7 8 9 10 | 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]} |
为了爱一行(注:效率极低!):
1 | d2 = {val: [key for key in d if val in d[key]] for lst in d.itervalues() for val in lst} |
1 2 3 4 5 6 7 8 9 | from collections import defaultdict second_dict = defaultdict(list) for key, value in first_dict.items(): for item in value: second_dict[item].append(key) |
1 2 3 4 5 6 7 8 9 | 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] |
1 2 3 4 5 6 7 8 9 | 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] |
在