Home > Blockchain >  Python using dictionary list values to key match a dictionary
Python using dictionary list values to key match a dictionary

Time:10-14

I'm struggling in python on how to query a dictionary with a value from one list as a key in another. For example:

d1 = {"fruit":[5, 3, 3, 3, 4, 2, 4]}

d2 = {0:"apple", 1:"pear", 2:"cherry", 3:"lime", 4:"orange", 5:"mango", 6:"kiwi"}

What I'd like to do is create a new dictionary where the fruits are still in a list like in d1 where there are multiples, but with key matched values from d2. Below is the transformation I am looking for. Kinda like an inner join in sql.

d3 = {"fruit":["mango", "lime", "lime", "lime", "orange", "pear", "orange"]}

I tried using the code below, but it just nested d2 as a dictionary within rather than matching each value in the list.

d3 = {k: d2 for k, v in d1.items()}
>>>{'fruit': {0: 'apple', 1: 'pear', 2: 'cherry', 3: 'lime', 4: 'orange', 5: 'mango', 6: 'kiwi'}}

I've been able to combine the two if I convert d1 into a list rather than a dictionary, however it doesn't carry over duplicate entries if there are more than one of each fruit.

l1 = [5, 3, 3, 3, 4, 2, 4]
d2 = {0:"apple", 1:"pear", 2:"cherry", 3:"lime", 4:"orange", 5:"mango", 6:"kiwi"}
d3 = {k: d2[k] for k in l1 if k in d2}
>>>{5: 'mango', 3: 'lime', 4: 'orange', 2: 'cherry'}

Any guidance would be greatly appreciated.

CodePudding user response:

Here is a solution written entirely by AI:

Solution

dict1 = {'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]}
dict2 = {1: 'x', 2: 'y', 3: 'z', 4: 'w', 5: 't', 6: 'u', 7: 'r', 8: 's', 9: 'v'}

dict3 = {k: [dict2[i] for i in v] for k, v in dict1.items()}

print(dict3)

Explanation

The solution uses a dictionary comprehension to create a new dictionary.

The dictionary comprehension iterates over the key-value pairs of dict1.

For each key-value pair, the key is assigned to k and the value is assigned to v.

The value of v is a list of integers.

The dictionary comprehension uses a list comprehension to create a new list.

The list comprehension iterates over the integers in v.

For each integer, the list comprehension uses the integer to look up the corresponding value in dict2.

The list comprehension returns a list of the values from dict2.

The dictionary comprehension returns a dictionary with the keys from dict1 and the values from dict2.

CodePudding user response:

You need to nest a list comprehension which maps the values from d2 onto the items in the list:

>>> {k:[d2[v] for v in vs] for k, vs in d1.items()}
{'fruit': ['mango', 'lime', 'lime', 'lime', 'orange', 'cherry', 'orange']}

Or, expressed another way:

>>> {k:list(map(d2.get, vs)) for k, vs in d1.items()}
{'fruit': ['mango', 'lime', 'lime', 'lime', 'orange', 'cherry', 'orange']}

(note, the above uses .get, so if the value is not in d2, it returns None

  • Related