Update a python dictionary w/ lists - python

I'm struggling to update a dictionary of lists using loops.
weather_dict = \
{
"texas": [],
"colorado": = [],
"virginia": = [],
"illinois": = [],
"california": = []
}
arbitrary_weather = [10, 20, 30, 40, 50]
My goal is to have the values of
arbitrary_weather
pushed into lists within the dictionary using loops. The correlation map is sequential, arbitrary_weather[0] --> texas[],
arbitrary_weather[1] --> colorado[], etc. With every iteration of the code, arbitrary_weather is going to change, but the dictionary will continue to append its lists in the same sequential order.
I'm relatively new to python, but working on a graduate project that is going to accumulate a lot of data over time. Eventually, the lists of data within the dictionary will be analyzed using python panda. I have never used panda, so if possible, it would be tremendously helpful to learn best practices for building dictionaries used in data analytics.
Thank you!

If you can make sure the the number of keys in dictionary always equal the len of the list then you can loop through the dictionary and add one at a time
weather_dict = {
"texas" : [],
"colorado" : [],
"virginia" : [],
"illinois" : [],
"california" : []
}
arbitrary_weather = [10, 20, 30, 40, 50]
i = 0
for k in weather_dict:
weather_dict[k].append(arbitrary_weather[i])
i += 1
print(weather_dict)
EDIT:
Note that python 3.6 and below iterate through dict is not ordered, if you using python 3.6 and below I suggest using the answer made by Mad Physicist of turning keys into a list so it's ordered

Keep in mind that until python 3.6, dictionaries were not ordered. In fact, you're only using your initial dict as a repository for key names, so I'd recommend storing it as a sequence of key names, not a dictionary with empty values:
states = ['Texas', 'Colorado', 'Illinois', 'California']
You can turn the initial measurements into a dictionary using a comprehension, and append to the lists after that:
weather_dict = {state: [value] for state, value in zip(states, arbitrary_weather)}
You can do that even if you keep the original dictionary as a dictionary, since it is iterable over the keys.

Related

Update data with list comprehension in Python?

I am working on a python assignment struggling with list comprehension. Basically this is the nested for loop I need to convert into a list comprehension function:
for driver in standings:
if driver['driver'] in drivers_with_points.keys():
driver['points'] = drivers_with_points[driver['driver']]
This is the question prompt:
"""Updates the < standings > list by adding the points from the given race < results >.
Using a list comprehension, updates each dictionary in < standings > at
the key 'points' with the points value retrieved from the < drivers_with_points >
dictionary.
Parameters:
standings (list): A list of dictionaries, each containing information about a
driver's standing.
drivers_with_points (dict): A dictionary containing the name and points scored
by each driver who scored points in a race.
Returns:
None
"""
The solution might look something like:
drivers_with_points = {"joe": 22, "dan": 123} # dummy data
drivers = [{"driver": "joe"}, {"driver": "dan"}] # dummy data
standings = [
{"points": drivers_with_points[driver["driver"]]}
for driver in drivers
if driver["driver"] in drivers_with_points.keys()
] # list comprehension
print(standings) # Output: [{'points': 22}, {'points': 123}]
I took my freedom to use some dummy-data here, as you did not provide any datasets the script is supposed to work with.

How to extract the given keys in one dictionary from another into a new dictionary (Python)

I'm trying to practice sets and dictionaries, and one thing I've been finding is myself stuck on this practice problem over and over.
For example if I have a dictionary like
employees =[
{
"name": "Jamie Mitchell",
"job": "Head Chef",
"city": "Toronto",
},
{
"name": "Michell Anderson",
"job": "Line Cook",
"city": "Mississauga",
}
]
How would I extract the second part of the dictionary from the first in order to only have the information on the right be in a new dictionary?
Quick Answer:
employees is a list of dictionaries so you can just directly index the list to get Michell:
newDict = employees[1]
More Detailed Answer:
Firstly, here is how you create a key-value pair in a dictionary:
dct = {}
dct['color'] = 'blue' # dct = {'color':'blue'}
Knowing this, all you would need to copy a dictionary is the keys and values. You can use the .keys(),.values(), and .items() methods of dictionaries to do this.
dct.keys() # returns a list of all the keys -> ['color']
dct.values() # returns a list of all the values -> ['blue']
dct.items() # return a list of all the pairs as tuples -> [('color','blue')]
There are other options to copy as another user has mentioned however I strongly suggest you get used to work with the 3 methods listed above. If you haven't already, make sure you are really comfortable with lists before you jump into dictionaries and combined structures. You already seem to know how to work loops so hopefully this is helpful enough, good luck!
You have them backwards; the outer one [] is a list. The inner ones {} are dictionaries.
You can get the second one with employees[1] (indexing starts from 0) or the last one with employees[-1] (in this case they are the same).
If you need a copy, you can call .copy() on the result:
second_employee = employees[1]
copied_details = second_employee.copy()

RuntimeError: dictionary changed size

I have two nested dictionaries. Each dictionary has a key/value pair that are the same. I have some code that says hey if these are the same, update an existing dictionary with another key/value combo that exists in one of the dictionaries to the other dictionary. I get the error RuntimeError: dictionary changed size during iteration. I've seen that you can use deepcopy to solve for this, but does anybody else have any other ideas?
performances = [
{'campaign_id': 'bob'},
{'campaign_id': 'alice'},
]
campaign_will_spend = [
{'id': 'bob'},
{'id': 'alice'},
]
for item in campaign_will_spend:
ad_dictt = dict()
for willspendkey, willspendvalue in item.items():
if willspendkey == "id":
for i in performances:
for key, value in i.items():
if key == 'campaign_id' and value == willspendvalue:
i['lifetime_budget'] = item
You're causing yourself a lot of trouble by treating dictionaries like lists and iterating over them in their entirety to find a particular item. Most of the code goes away when you just stop doing that, and the rest of it goes away if you build a dictionary to be able to easily look up entries in campaign_will_spend:
# Easy lookup for campaign_will_spend dictionaries by id.
cws_by_id = {d['id']: d for d in campaign_will_spend}
for p in performances:
p["lifetime_budget"] = cws_by_id[p["campaign_id"]]

How can I automate making dictionaries using python?

I am doing a beginners Python course and the aim is to make a bunch of dictionaries.
Create three dictionaries: lloyd, alice, and tyler.
Give each dictionary the keys "name", "homework", "quizzes", and
"tests".
Have the "name" key be the name of the student (that is, lloyd's name
should be "Lloyd") and the other keys should be an empty list (We'll
fill in these lists soon!)
I did this by doing the following:
def make_dict(list_of_names):
for names in list_of_names:
names = {
"name": names,
"homework" : [],
"quizzes" : [],
"tests" : []
}
list_of_names = ["lloyd", 'alice', 'tyler']
make_dict(list_of_names)
Why does this not work? Should it work and is it just the Codeacademy development area that does not allow this to work? I realise I am being a little extra and that I could do this really straightforwardly and am purposely trying to be creative in how I do it.
In any case, what is the automated way to make a dictionary, based on lists of inputs?
You're creating a dictionary called names in each loop but not actually doing anything with it --
def make_dict(list_of_names):
results = []
for names in list_of_names:
names = {
"name": names,
"homework" : [],
"quizzes" : [],
"tests" : []
}
results.append(names)
return results
list_of_names = ["lloyd", 'alice', 'tyler']
my_dicts = make_dict(list_of_names)
This keeps track of the names dicts you have created, and then gives them to you at the end.
What is the automated way to make a dictionary, based on lists of
inputs?
You can use a dictionary comprehension here. A generator can avoid the need for boilerplate list construction code. In this solution, we yield items for each name in a list. Calling list then exhausts the generator, and we can assign the list to the variable my_dicts.
def make_dict(lst):
for name in lst:
d = {k: [] for k in ('homework', 'quizzes', 'tests')}
d['name'] = name
yield d
list_of_names = ['lloyd', 'alice', 'tyler']
my_dicts = list(make_dict(list_of_names))
You are creating three dictionaries; however, each one overwrites the previous one by assigning to the same variable names, and the last one is garbage collected because the only reference to it is a local variable that goes out of scope when make_dict returns.
You just need to return the created dict. For this exercise, it doesn't sound like you really need a loop.
def make_dict(name):
return {
"name": name,
"homework" : [],
"quizzes" : [],
"tests" : []
}
lloyd = make_dict("lloyd")
alice = make_dict("alice")
tyler = make_dict("tyler")
Vegetables={"tamato":40,"carrot":50,"onion":60,"green chillies":20,"red chillies":40,"capsicum":20,"radish":30,"drumstick":40,"beetroot":50,"peas":90}
Print(vegetables)

Appending something to a list within a dict within a list in Python

I am attempting to create a list of dicts which will have the following structure:
[
{
'id': '234nj233nkj2k4n52',
'embedded_list': []
},
{
'id': 'jb234bhj23423h4b4',
'embedded_list': []
},
...
]
Initially, this list will be empty.
What I need to be able to do is:
Check to see if a dict with a specific id exists in the list already
If a dict containing that id exists, append something to it's embedded_list
If a dict containing that id does not exist, create a dict, append it to the list.
I am aware of being able to test if a dict exists in a list based on something inside that dict using something like this:
extracted_dict = next((item for item in list if item['id'] == unique_id), None)
I am unsure of how to append something to a list within a dict within a list efficiently. Is there an obvious way which I'm not seeing (probably)?
Thank you in advance.
Your data structure should be a dictionary of dictionaries in the first place:
{'234nj233nkj2k4n52': {'embedded_list': []},
'jb234bhj23423h4b4': {'embedded_list': []},
... }
This will make all your desired operations much easier. If the inner dictionaries only contain the embedded list, this can be further simplified to
{'234nj233nkj2k4n52': [],
'jb234bhj23423h4b4': [],
... }
Now, all you need is a collections.defaultdict(list):
from collections import defaultdict
d = defaultdict(list)
d['234nj233nkj2k4n52'].append(whatever)
or just a simple dic
{
'234nj233nkj2k4n52' : [],
'jb234bhj23423h4b4' : []
}

Categories