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'}
Related
I was trying to iterate over a list of values, craft a dictionary to save each value in a structured way, and then append the dictionary to a new list of results, but I found an unexpected behavior.
Below is an example:
values_list = [1,2,3]
# Basic dict
result_dict = {
'my_value': ''
}
# Iterate, craft a dictionary, and append result
dicts_list = []
for value in values_list:
result_dict.update({'my_value': value})
dicts_list.append(result_dict)
print(dicts_list)
As you can see, first I create a basic dictionary, then I'm iterating over the list of values and updating the dictionary, at the end I'm appending the crafted dictionary to a separate list of results (dicts_list).
As a result I was expecting:
[{'my_value': 1}, {'my_value': 2}, {'my_value': 3}]
but instead I was getting:
[{'my_value': 3}, {'my_value': 3}, {'my_value': 3}]
It looks like every iteration is not only updating the basic dictionary – which is expected – but also the dictionaries already appended to the list of results on the previous iteration.
To fix the issue, I nested the basic dictionary under the for loop:
values_list = [1,2,3]
# Iterate, craft a dictionary, and append result
dicts_list = []
for value in values_list:
result_dict = {'my_value': ''}
result_dict.update({'my_value': value})
dicts_list.append(result_dict)
print(dicts_list)
Can anyone explain what is wrong with the first approach? How is the loop causing the list of appended dictionaries to be updated?
Thanks for any advice! :)
Franz
As explained in the comment, you're appending the same dictionary in each iteration because update() modifies the result_dict rather than returning a copy. So, the only change you need to do is to append a copy of the crafted dictionary. For example:
values_list = [1,2,3]
# Basic dict
result_dict = {
'my_value': ''
}
# Iterate, craft a dictionary, and append result
dicts_list = []
for value in values_list:
result_dict.update({'my_value': value})
dicts_list.append(dict(result_dict)) # <--- this is the only change
print(dicts_list)
To gain understanding of How is the loop causing the list of appended dictionaries to be updated? you can use Python Tutor: Visualize code in Python with the code you provided in your question to see the effect of executing the code line by line with the final result being following visualization:
I suggest you read also Facts and myths about Python names and values.
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.
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]
I am attempting to pull the key/value pairs from two specific items in JSON data
The data looks like this:
[{"voc": "UAT",
"concepts":[{"prefLabel":"Solar system",
"uri":"http://astrothesaurus.org/uat/1528", "score":"15" },
{"prefLabel":"X-ray astronomy",
"uri":"http://astrothesaurus.org/uat/1810", "score":"9" },
{"prefLabel":"Gamma-ray astronomy",
"uri":"http://astrothesaurus.org/uat/628", "score":"9" }
]}]
I am only trying to retrieve the prefLabel and score using a for-loop that will save them to a tuple to later be appended to my currently empty data list.
This is my current loop but it returns a 'wrong type' error:
for concepts in voc_list:
for prefLabel, score in concepts.items():
data_tuple = (prefLabel, score)
data.append(data_tuple)`
Any help is appreciated
You could search the list of dictionaries, and append to the data list when the key matches the desired string:
for d in voc_list[0]['concepts']:
for k, v in d.items():
if k == 'prefLabel':
data.append((k, v))
I have a dictionary that looks like:
{u'message': u'Approved', u'reference': u'A71E7A739E24', u'success': True}
I would like to retrieve the key-value pair for reference, i.e. { 'reference' : 'A71E7A739E24' }.
I'm trying to do this using iteritems which does return k, v pairs, and then I'm adding them to a new dictionary. But then, the resulting value is unicode rather than str for some reason and I'm not sure if this is the most straightforward way to do it:
ref = {}
for k, v in charge.iteritems():
if k == 'reference':
ref['reference'] = v
print ref
{'reference': u'A71E7A739E24'}
Is there a built-in way to do this more easily? Or, at least, to avoid using iteritems and simply return:
{ 'reference' : 'A71E7A739E24' }
The trouble with using iteritems is that you increase lookup time to O(n) where n is dictionary size, because you are no longer using a hash table
If you only need to get one key-value pair, it's as simple as
ref = { key: d[key] }
If there may be multiple pairs that are selected by some condition,
either use dict from iterable constructor (the 2nd version is better if your condition depends on values, too):
ref = dict(k,d[k] for k in charge if <condition>)
ref = dict(k,v for k,v in charge.iteritems() if <condition>)
or (since 2.7) a dict comprehension (which is syntactic sugar for the above):
ref = {k,d[k] for k in charge if <condition>}
<same as above>
I dont understand the question:
is this what you are trying to do:
ref={'reference',charge["reference"]}