Match dictionary values back into dictionary - python

I am performing a math operation on two dictionaries and I want to take the output of these dictionaries and map them back into another dictionary.
I have some working code that outputs my expected value but not into the key : value pair that I am interested in.
I have two dictionaries:
dict1
{'outer': {'word1':0.1234, 'word2':0.4321, 'word3':0.4567 } }
dict2
{'word1':2.222,'word3':3.567,'word2':2.123}
I have this code to multiply the values of word1 with word1 in their respective dictionaries:
new_dict=dict()
pkeys=dict1.keys()
for key in pkeys:
for entry in dict1[key]:
new_dict[entry]= dict1[key][entry] * dict2[entry]
new_dict contains the correct output:'word1': 0.27419, but I can't seem to get it back into the format in
dict1: {'outer':{'word1':0.27419, 'word2':0.91734 }

You can use the dict.setdefault method to initialize a sub-dict for new_dict under the current key in the iteration.
Change:
new_dict[entry]= dict1[key][entry] * dict2[entry]
to:
new_dict.setdefault(key, {})[entry]= dict1[key][entry] * dict2[entry]

Related

Nested Dictionary (JSON): Merge multiple keys stored in a list to access its value from the dict

I have a JSON with an unknown number of keys & values, I need to store the user's selection in a list & then access the selected key's value; (it'll be guaranteed that the keys in the list are always stored in the correct sequence).
Example
I need to access the value_key1-2.
mydict = {
'key1': {
'key1-1': {
'key1-2': 'value_key1-2'
},
},
'key2': 'value_key2'
}
I can see the keys & they're limited so I can manually use:
>>> print(mydict['key1']['key1-1']['key1-2'])
>>> 'value_key1-2'
Now after storing the user's selections in a list, we have the following list:
Uselection = ['key1', 'key1-1', 'key1-2']
How can I convert those list elements into the similar code we used earlier?
How can I automate it using Python?
You have to loop the list of keys and update the "current value" on each step.
val = mydict
try:
for key in Uselection:
val = val[key]
except KeyError:
handle non-existing keys here
Another, more 'posh' way to do the same (not generally recommended):
from functools import reduce
val = reduce(dict.get, Uselection, mydict)

Check for string in list items using list as reference

I want to replace items in a list based on another list as reference.
Take this example lists stored inside a dictionary:
dict1 = {
"artist1": ["dance pop","pop","funky pop"],
"artist2": ["chill house","electro house"],
"artist3": ["dark techno","electro techno"]
}
Then, I have this list as reference:
wish_list = ["house","pop","techno"]
My result should look like this:
dict1 = {
"artist1": ["pop"],
"artist2": ["house"],
"artist3": ["techno"]
}
I want to check if any of the list items inside "wishlist" is inside one of the values of the dict1. I tried around with regex, any.
This was an approach with just 1 list instead of a dictionary of multiple lists:
check = any(item in artist for item in wish_list)
if check == True:
artist_genres.clear()
artist_genres.append()
I am just beginning with Python on my own and am playing around with the SpotifyAPI to clean up my favorite songs into playlists. Thank you very much for your help!
The idea is like this,
dict1 = { "artist1" : ["dance pop","pop","funky pop"],
"artist2" : ["house","electro house"],
"artist3" : ["techno","electro techno"] }
wish_list = ["house","pop","techno"]
dict2={}
for key,value in dict1.items():
for i in wish_list:
if i in value:
dict2[key]=i
break
print(dict2)
A regex is not needed, you can get away by simply iterating over the list:
wish_list = ["house","pop","techno"]
dict1 = {
"artist1": ["dance pop","pop","funky pop"],
"artist2": ["chill house","electro house"],
"artist3": ["dark techno","electro techno"]
}
dict1 = {
# The key is reused as-is, no need to change it.
# The new value is the wishlist, filtered based on its presence in the current value
key: [genre for genre in wish_list if any(genre in item for item in value)]
for key, value in dict1.items() # this method returns a tuple (key, value) for each entry in the dictionary
}
This implementation relies a lot on list comprehensions (and also dictionary comprehensions), you might want to check it if it's new to you.

Extracting values from old dictionary into new dictinary using iteration

I am struggling to figure out an assignment.
The problem set up is:
I have a list containing ratios ( unique_ratio = ['0.05', '0.98', '1.45']
I have a dictionary containing k:v as ratio:count the number of times ratio has appeared in a previous variable ( dict = {'0.05':'5', '0.32':'72', '0.98': '21'}
I want to iterate over the dictionary and extract the k:v for the ratios which appear in the unique_ratio list. I want to store these k:v's in a new dictionary (frequencies = {})
I am running pytho 3.7
I have tried iterating over the dictionary using for loop but am never able to extract the k:v pair.
I am unsure whether I should test for i in unique_ratios or i in dict
for i in dict.values():
frequencies = { k:v for k,v in comp_dict_count.items() if 'i' in
unique_ratios }
print(frequencies)
Everything I have tried has led to syntax errors. The above code leads to empty frequencies dictionary.
You need a single dictionary comprehension for this. Also for a better formormance you could check membership using sets, reducing the lookup complexity to O(1):
unique_ratio = set(['0.05', '0.98', '1.45'])
d = {'0.05':'5', '0.32':'72', '0.98': '21'}
{k:v for k,v in d.items() if k in unique_ratio}
# {'0.05': '5', '0.98': '21'}

Create Python list from key in dict

If I have a dict in Python like the following:
d = {'hello': [{a:1, b:2, c:3}, {a:4, b:5, c:6},{a:7, b:8, c:9}]}
I'd like to create an array that will give me all the values of "b". Short of iterating over the array for key "hello", is there an easy way to do this?
Use a list comprehension:
b_list = [subdict[b] for subdict in d['hello']]
Iterate over all the sub-dictionaries in the value stored by hello and access the value stored by the key b.

Inverse Dict in Python

I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
and I would like to obtain:
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
So far, I've not been able to do this in a very clean way. Any suggestions?
If you are using Python 2.5 or above, use the defaultdict class from the collections module; a defaultdict automatically creates values on the first access to a missing key, so you can use that here to create the lists for dict2, like this:
from collections import defaultdict
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
dict2 = defaultdict(list)
for key, values in dict1.items():
for value in values:
# The list for dict2[value] is created automatically
dict2[value].append(key)
Note that the lists in dict2 will not be in any particular order, as a dictionaries do not order their key-value pairs.
If you want an ordinary dict out at the end that will raise a KeyError for missing keys, just use dict2 = dict(dict2) after the above.
Notice that you don't need the dict in your examples: the {} syntax gives you a dict:
dict1 = {'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]}
Other way:
dict2={}
[[ (dict2.setdefault(i,[]) or 1) and (dict2[i].append(x)) for i in y ] for (x,y) in dict1.items()]

Categories

Resources