Create Python list from key in dict - python

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.

Related

Update Python dictionary while looping

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.

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.

How can retreive list of all keys in dictionary in Python?

I have a dictionary in Python with some keys and their values. like-
states = {"Rajasthan": "Jaipur", "Madhyapradesh" :"Bhopal", "Maharashtra" : "Mumbai", "Tamilnadu": "Chennai" }
I want to retrieve list of all keys of this dictionary like -
["Rajasthan", "Madhyapradesh", "Maharashtra", "Tamilnadu"]
How can i do this.
You can use list comprehension as following
keys = [i for i in states]
or
using list function that will convert states keys to a list
list(states)
and you will get
['Rajasthan', 'Madhyapradesh', 'Maharashtra', 'Tamilnadu']

Match dictionary values back into dictionary

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]

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