How to get the value of a value as a key of a dict

2019-07-24 17:12发布

问题:

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]}

and I want to show that 1 is a key and is also a value, thereby getting to the conclusion that 0 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.

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.

回答1:

Do you mean something like this?

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

gives

>>> d
{0: (1, 2, 3, 2, 3, 4, 5, 6, 7), 1: (2, 3, 4, 5, 6, 7), 2: (5, 6, 7)}

If you want unique values then add d[key] = tuple(set(d[key])) to the end of the for key in d.keys() loop.

gives

>>> 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]} is not valid python!

edit: see comments.

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))

gives

>>> d
{0: [4, 5, 6, 7], 1: [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))

which gives

>>> d
{0: [4, 5, 6, 7], 1: [5, 6, 7], 2: [5, 6, 7]}

edit 2: see comments.

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))


回答2:

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