我不确定之前是否曾经问过这个问题,因为我也不知道怎么说:
所以例如我有一个带键和值的字典:
d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}
我希望证明1是一个关键,也是一个值,从而得出结论 0连接到值1.如[0:[2,3,4],2,3]或类似的东西。
我会为大量的密钥执行此操作,每个密钥都有多个值。
这可能吗?我将如何编码呢?顺便说一下,我是Python的新手,所以请放轻松。
答案 0 :(得分:0)
你的意思是这样吗?
d = { 0 : (1, 2, 3) , 1 : (2, 3, 4), 2: (5, 6, 7)}
for key in d.keys():
for val in d[key]:
try:
d[key]+=d[val]
except KeyError:
pass
给出
>>> d
{0: (1, 2, 3, 2, 3, 4, 5, 6, 7), 1: (2, 3, 4, 5, 6, 7), 2: (5, 6, 7)}
如果您想要唯一值,请将d[key] = tuple(set(d[key]))
添加到for key in d.keys()
循环的末尾。
给出
>>> d
{0: (1, 2, 3, 4, 5, 6, 7), 1: (2, 3, 4, 5, 6, 7), 2: (5, 6, 7)}
ps:d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}
无效python!
编辑:见评论。
d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
orig_vals=d[key]
new_vals=[]
for val in orig_vals:
try:
new_vals+=d[val]
except KeyError:
pass
d[key] = list(set(new_vals)-set(orig_vals))
给出
>>> d
{0: [4, 5, 6, 7], 1: [5, 6, 7], 2: []}
如果您想避免清除未链接到其他键的值,例如[5,6,7]在2中,然后将最后一行改为
if new_vals:
d[key] = list(set(new_vals)-set(orig_vals))
给出了
>>> d
{0: [4, 5, 6, 7], 1: [5, 6, 7], 2: [5, 6, 7]}
编辑2:看评论。
d = { 0 : [1, 2, 3] , 1 : [2, 3, 4], 2: [5, 6, 7]}
for key in d.keys():
orig_vals=d[key]
new_vals=[]
count = 0
for val in orig_vals:
try:
new_vals+=d[val]
count+=1
if count >= yournumberhere: break
except KeyError:
pass
d[key] = list(set(new_vals)-set(orig_vals))
答案 1 :(得分:0)
d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]} this is not a valis dictionary
It will be like this:
d={0: [1, 2, 3], 1: [2, 3, 4], 2: [5, 6, 7]}
arr=[]
for val in d.values():
arr.extend(val)
arr = [1, 2, 3, 2, 3, 4, 5, 6, 7]
values=set(arr) #removeing repeted element from the list
value = [1, 2, 3, 4, 5, 6, 7]
result = [key for key in d.keys() if key in values] #will return the result
result = [1, 2]
here result = [1,2] so,1 and 2 is a key and also a vaule