Update data with list comprehension in Python? - 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.

Related

Python List of Dictionaries to new Dictionary or List

Pardon the noob question, I am new to Python.
I am working with a list of dictionaries:
dataset = [
{'id':1,'dateCollected':'2021-03-02','orders':7},
{'id':2,'dateCollected':'2021-03-03','orders':8},
]
.... this goes on for 50 records ....
I would like to a make a for loop that iterates through every dictionary in the list and adds certain key-value pairs to a new dictionary.
For Example:
match_history_data = {}
for i in dataset:
match_history_data['DateCollected'] = i['dateCollected']
match_history_data['Orders'] = i['orders']
print(match_history_data)
results in:
{'DateCollected': '2021-03-03', 'Orders': 8}
I would like the result to be:
{'DateCollected':'2021-03-02','Orders':7},
{'DateCollected':'2021-03-03','Orders':8}
This works how I want it to, but only for the first iteration in the for loop. How do I get around this so that it goes thru all the records in 'dataset', and creates the new list or dictionary?
You're creating a new dictionary, match_history_data and then just setting the same entries 'DateCollected' and 'Orders' over and over again. Each iteration of your for loop is just overwriting the same entries.
What you want is a list of new dictionaries:
match_history_data = []
for item in dataset:
match_history_data.append(
{"DateCollected" : item["dateCollected"],
"Orders" : item["orders"]})
You can achieve this in a neater fashion using a list comprehension:
match_history_data = [{"DateCollected" : item["dateCollected"], "Orders" : item["orders"]} for item in dataset]
How about this
match_history_data = [{"DateCollected":x["dateCollected"], "Orders":x["orders"]} for x in dataset]
What you have right now overwrites a single dictionary as your loop through the original list of dictionaries, since keys are unique in dictionaries. What you need to is another list to which you can append the new dictionaries during each iteration to a separate list.
For example
new_list = []
for i in dataset:
match_history_data = {}
match_history_data['DateCollected'] = i['dateCollected']
match_history_data['Orders'] = i['orders']
new_list.append(match_history_data)
If you don't want to preserve the original list, you can simply drop the id key in each dictionary.

Querying from CSV files using python

I have three CSV files, one has a list of all pieces, one has a list of pieces of type M and the other one of type B. That means the first list contains the two other ones but without specifying their type.
I want to add a row to the frist list that specifies the type of pieces using python, that means for each piece in the first list, check if it's in list M and add an M in its type column, otherwise add a B.
My idea was to create a list of dictionaries (that I can convert later to CSV using a pre-written Python library), it would look something like this:
l = [{'piece','type'}] # list of dictionaries
for c in allpieces: # this is the list of all pieces:
l[{'piece'}] = c['piece'] # adding the piece number to the list of dictionaries from the list of all pieces
for m in mlist: # list of pieces of type m
if c['piece'] == m['piece']: # check of piece is found in listm
l[{'type'}] = 'm' # Add an m in its column
else: l[{'type'}] = 'b' # otherwise add b
This code is obviously not doing anything, and I need help debugging it.
A dictionary maps a key to a value like so {"key": "value} whereas elements in a list are accessed by providing the index so for first element in a list you do list[0] to get it. Now if you want to add new keys with values to a dictionary you can do it by adding them like such d["key"] = value. If you want to add to your list you do list.append(value). So in your case what you want to do is create a list with dictionaries inside I assume ? So that could look like that:
allpieces = ["Queen", "Tower", "Rook"]
mlist = ["Pawn", "Queen", "Rook"]
l = []
for c in allpieces:
if c in mlist:
l.append({"piece": c, "type": "m"})
else:
l.append({"piece": c, "type": "b"})
print(l)
Which creates a list with our dictionaries inside as such:
[{'piece': 'Queen', 'type': 'm'}, {'piece': 'Tower', 'type': 'b'}, {'piece': 'Rook', 'type': 'm'}]
Now if you were to access elements within this list you would do l[0]["piece"] to get "Queen"

name variables or append dictionaries

I am trying to either
create dictionaries names based on loop index e.g. mydict_1, mydict_2 etc.
or
append dictionaries in one dictionary
Through a loop I am getting sets of data and I want to be able to access them all at once or one by one.
for components in fiSentence.findall("components"):
operation = components.find('operation').text
target = components.find('target').text
targetState = components.find('targetState').text
...
all this going in a dictionary:
tempDict = {"operation":operation, "target":target, "targetState":targetState, ...}
and then outside of the loop I tried to store all of them in another dictionary but I only managed to do so with a list:
data.append(tempDict)
What I want is either to store them in different dictionaries as:
procedural_Step_1 = {"operation":operation, "target":target, "targetState":targetState}
procedural_Step_2 = {"operation":operation, "target":target, "targetState":targetState}
...
or
store them all in one dictionary of dictionaries:
data = {"procedural_Step_1":{"operation":operation, "target":target, "targetState":targetState}, {"procedural_Step_2":{"operation":operation, "target":target, "targetState":targetState},...}
You can declare dict data before the loop and in the end of loop:
data['procedural_step_'+str(index)] = temp_dict
Index you can get with enumerate

Update a python dictionary w/ lists

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.

Update dictionary key based on value

I have the following dictionary:
players = {'Roger': ['player1', 'dA'], 'Luka': ['player2', 'sK']}.
I want to update the key that contains 'player2', but
I can't update players[Luka] because 'player2' is not always Luka. How can I select keys linked to 'player2'?
(for those wondering, dA = Ace of Diamonds, sK = King of Spades. These values will also be different every time).
Edit:
Here's the part of my code: (It won't run because I left out a lot of clutter)
qPlayers = 2 #Amount of players
def game(qPlayers):
players[nr]["value"].append(new_card)
deal_to =[]
for player in players:
deal_to.append(player)
deal(qPlayers,deck,players,deal_to)
def setup(qPlayers):
playerhands = []
for x in range(1,qPlayers+1):
player = {}
player["name"] = input("Enter your name, player {}\n>>>".format(x))
playerhands.append(player)
return playerhands
def deal(qPlayers,deck,players,deal_to):
nr = -1
for player in deal_to:
nr +=1
new_card = getCard(deck) #getCard produces a random card like sA, k9, cQ
You can keep track of which key in the dict contains your player2 value, or else you will have to iterate through the dict until you find a key that does. If you frequently need to search based on something internal to the value, you may want to reconsider the data structure you are using to store this data.
def findKeyWithValue(value):
for playerName, playerData in players.items():
if value in playerData:
# your code here
You have two options here:
Search through the entire directory, checking for the value which contains 'player2'. This ends up being inefficient, and makes the dictionary structure somewhat useless.
Use a list instead of a dictionary, and model your data accordingly, similar to the example below.
An advantage of this data structure is that you don't need the redundant player1/player2 identifiers, since the list index provides that implicitly. To reference player2 you'd take the second element from the list (players[1] since indexing starts at 0).
players = [
{'Name' : 'Roger', 'Value' : 'dA'},
{'Name' : 'Luka', 'Value' : 'sK'}
]
You can iterate the dictionary to find the key to update. dict.iteritems() will do that job in python 2.7.
players = {'Roger': ['player1', 'dA'], 'Luka': ['player2', 'sK']}
for key, value in players.iteritems():
if value[0] == "player2":
players[key][1] = "sQ"
print players

Categories