Python List, Dictionary Approach Question

Asked 1 years ago, Updated 1 years ago, 113 views

x = {'a': ['aaa', 'bbb'], 'b': ['aaa', 'ccc'], 'c': ['bbb', 'ccc']}
y = []
for i in x['a']:
    if i in x['c']:
        y.append(i)
        print(y)

If you write it like this, only ["bbb"] comes out I want to print 'a' and 'c' to which 'bbb' belongs. For example, 'a', 'c' : [bbb] Like this.

And I checked only 'a', the key value of one of the dictionary x in the for statement, but I want to check all of them by putting x, so how can I compare and express all of them?

(I made 3 combinations of 2 using cobinations, but I failed because I couldn't access the value.)

Please give me some advice. Thank you.

Desired output value

'aaa' : 'a', 'b'

'bbb' : 'a', 'c'

'ccc' : 'b', 'c'

python list dictionary

2022-09-22 18:47

1 Answers

>>> x = {'a': ['aaa', 'bbb'], 'b': ['aaa', 'ccc'], 'c': ['bbb', 'ccc']}
>>> all_val = set(x['a']) | set(x['b']) | set(x['c'])
>>> all_val
{'aaa', 'ccc', 'bbb'}
>>> for e in sorted(all_val):
    ks = [ k for k, v in x.items() if e in v ]
    if ks:
        print('%s : %s'%(e, ', '.join(ks)))


aaa : a, b
bbb : a, c
ccc : b, c


2022-09-22 18:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.