2 回答
TA贡献1744条经验 获得超4个赞
您可以构建一个包含每对键和值的集合,并从中构建字典条目:
dict1 = {
'a':['b','c'],
'd':['e','f']
}
sets = [set([key]) | set(values) for key, values in dict1.items() ]
# [{'a', 'b', 'c'}, {'f', 'd', 'e'}]
out = {}
for s in sets:
for key in s:
out[key] = list(s-set([key]))
print(out)
输出:
{'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['a', 'b'],
'f': ['d', 'e'], 'd': ['f', 'e'], 'e': ['f', 'd']}
TA贡献1877条经验 获得超6个赞
以下方法有效:
dict1 = {
'a':['b','c'],
'd':['e','f']
}
dict2 = { }
for k, v in dict1.items():
for x in v:
v_copy = v[:]
v_copy.remove(x)
dict2.update({x: [k] + v_copy})
dict1.update(dict2)
print(dict1)
添加回答
举报