问题描述
我不确定是否曾经问过这个问题,因为我也不知道该怎么写:
I'm not sure if this has been asked before since I also don't know how to word it:
例如,我有一个给定的字典,其中包含键和值:
So for example i have a given dictionary with keys and values:
d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}
,我想证明1是一个键,也是一个值,因此得出以下结论:0连接到值1,例如[0:[2,3,4],2、3]或类似的东西.
and I want to show that 1 is a key and is also a value, thereby getting to the conclusion that0 is connected to the value of 1. like [0:[2,3,4], 2, 3] or something like that.
我将对大量键(每个键具有多个值)执行此操作.
And I would be doing this for a large amount of keys, each with multiple values.
这可能吗?我该怎么编码呢?顺便说一下,我是Python的新手,所以请放轻松.
Is this possible? And how would I code that? By the way, I'm very new to Python so please take it easy on me.
推荐答案
您的意思是这样的吗?
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)}
如果要使用唯一值,请在for key in d.keys()
循环的末尾添加d[key] = tuple(set(d[key]))
.
If you want unique values then add d[key] = tuple(set(d[key]))
to the end of the for key in d.keys()
loop.
给予
>>> 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!
ps: d = {[ 0 : 1, 2, 3], [1 : 2, 3, 4], [2: 5, 6, 7]}
is not valid 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 you want to avoid clearing values that were not linked to other keys, e.g. [5,6,7] in 2, then change the last line to
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]}
查看评论.
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))
这篇关于如何获取值的值作为字典的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!