Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Assume, I have a dictionary A, and list B. Do I need to get a key from A dictionary if B is subset A.values()

A={1: 'jendela', 2: 'jendela', 3: 'kursi', 4: 'meja', 5: 'pintu', 6: 'payung'}

B=set(['jendela','kursi'])

c=[[1,3],[2,3]]

>> B.issubset(A.values())

>> True

Yet, how I get list C. C is yield model on the off chance that I have dictionary A and list B

1 Answer

0 votes
by (26.4k points)

On the off chance that I see effectively, you need to create a list of all sets of keys into the dictionary A that will query all the values in your set B

The principal thing you need is a posting of the keys for each value you need. For that, I think you truly need to switch your A mapping. Rather than planning from a number to a string, map from a string to a rundown of numbers:

A = {1: 'jendela', 2: 'jendela', 3: 'kursi', 4: 'meja', 5: 'pintu', 6: 'payung'}

A_reversed = collections.defaultdict(list)

for number, string in A.items():

    A_reversed[string].append(number)

Presently, use itertools.product to join the necessary records together: 

result_gen = itertools.product(*(A_reversed[string] for string in B))

This outcome is a generator, on the off chance that you need a list, use list(result_gen) (or simply incorporate list call bring in the line above). 

On the off chance that one of the qualities from B doesn't show up as a value in A, you'll get vacant outcomes.

Are you looking for a good python tutorial? Join the python course fast and gain more knowledge in python.

Related questions

0 votes
4 answers
0 votes
1 answer
0 votes
4 answers

Browse Categories

...