我试图将字典中的键和值匹配在一起,并将它们放入新字典中。
我最初的字典是这样的:
d = {1: [5,6], 3: [4], 8: [2,3]}
我知道我可以使用 d.keys()
和 d.values()
访问键和值。
我的目标是找到所有相关的项目。我认为如果我说明我想要的输出是最好的解释。
我希望创建一个新的 dict 给我:
finaldict = {1: [5,6], 2: [3,4,8], 3: [2,4,8], 4:[2,3,8] 5:[1,6], 6:[1,5], 8:[2,3,4]}
也就是我要获取所有数字的键,并赋值给它们所关联的数字。
我的尝试:
d = {1: [5,6], 3:[4],8:[2,3]}
print(d)
keys = list(d.keys())
vals = list(d.values())
for i in range(0,len(d.keys())):
current_vals = list(vals[i])
length = len(current_vals)
for v in current_vals:
if v in d.keys(): #if the dictionary exists, then append
add = [keys[i],current_vals]
d[v].append(add)
else:
add2 = [keys[i],current_vals]
empty = []
for a in add2:
if type(a) == int:
empty.append(a)
if type(a) == list:
for b in a:
empty.append(b)
d[v] = empty
keys = list(d.keys())
vals = list(d.values())
for i in range(0,len(keys)):
if keys[i] in vals[i]:
vals[i].remove(keys[i])
finaldict = {}
for j in range(0,len(keys)):
finaldict[keys[j]] = vals[j]
print("Final dict:\n",finaldict)
我的尝试给了我输出
Final dict:
{1: [5, 6], 3: [4, [8, [2, 3]]], 8: [2, 3], 5: [1, 6], 6: [1, 5], 4: [3], 2: [8, 3]}
如您所见,finaldict[3]
的值为 [4, [8, [2, 3,]]]
。
值本身是错误的(3 不应该在那里),而且我希望这是一个单一的列表,而不是现在的格式。还有其他问题,例如 finaldict[2]
具有值 [8, 3]
而实际上它应该具有值 [3, 4, 8]
和 finaldict[4]
只有 [3]
,而它应该有 [2, 3, 8]
.
最佳答案
这不是我写过的最漂亮的代码,但就在这里。
我用所有相互关联的数字创建集合,然后创建一个字典,其中每个数字作为键,其他数字作为值。
d = {1: [5,6], 3: [4], 8: [2,3]}
pools = []
for key,values in d.items():
for pool in pools:
if key in pool or any(val in pool for val in values):
pool.add(key)
[pool.add(val) for val in values]
break
else:
pools.append(set((key, *values)))
#pools = [{1, 5, 6}, {8, 2, 3, 4}]
finaldict = {k:set.difference(v, set((k,))) for pool in pools for k, v in zip(pool, [pool]*len(pool))}
print(finaldict)
关于python - 匹配新字典中的字典键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66280604/