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)
添加回答
舉報