Dictionary is getting overriden while adding another entry - python

I have a function to create dictionary
def Bowler_creator (Name):
"""
This function will create the dictionaries for the batting player
"""
global bowler;
bowler = {
Name : { "number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
},
}
Current_Bowler = input("Enter the bowler's name\n");
Bowler_creator(Current_Bowler);
Bowler_creator('jafda');
My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary
So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?

You are replacing the dictionary with an entirely new dictionary each time.
You should create the dictionary once, then add keys:
bowler = {}
def Bowler_creator (Name):
bowler[Name] = {
"number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
}
Note: because the function no longer needs to assign a new object to bowler, you don't need to mark it as a global either. Assigning directly to the key modifies the global dictionary directly.

You are creating a new dictionary every time in the function Bowler_creator.
Try doing
bowler[Name] = { "number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
}

Related

Python - How to change dictionary value dynamically

I am trying to use a dictionary in such a way so that it returns a value dynamically. The following code should print "hello" first, then "world". As of now, it prints "hello" two times. Is there a way for me to use this dictionary dynamically?
val = "hello"
test = {
"A" : val
}
print(test["A"])
val="world"
print(test["A"])
I am thinking that this is not correct use of dictionaries. Could you please the whole task?
You can also check values and change the dictionary value
val = "hello"
test = {
"A" : val
}
print(test["A"])
val="world"
if test["A"]!=val: test["A"]=val
print(test["A"])
instead of val="world" use test["A"] = "world"
val = "world" assigns a new string to the variable, but doesn't change the existing string. The dictionary test however keeps the old string value, not a reference to the val variable. You need to use another mutable data structure if you want to update the dictionary like this. Just for illustration, I show how a list would work:
val = ["hello"]
test = { "A" : val }
print(test["A"][0])
val[0] = "world"
print(test["A"][0])
Unlike a string, a list can be updated. test keeps the same (list) value as val (there is only one list in this example), but val is changed internally.
Note that you must not use val = ["world"], as this would again just assign a new list to val, but leave test unchanged, i.e. still refer to the old list containing "hello".

What does this piece of Python code do? I saw it and it confused me

capitals[add] = capitals.get(add, "?")
Im confused as to what that does. Can anyone explain to me what its doing?
The assignment in that code is equivalent to this alternative, which explicitly tests for the existence of the key held in the variable add in the dictionary:
if add not in capitals:
capitals[add] = "?"
The original code you asked about uses different logic by utilizing the dict.get method to get either the existing value (if there is one) for the key add, or the string "?" if that key doesn't exist in the dictionary. In either case, it unconditionally updates the dictionary (either with the same value it had, or the new default). Afterwards, you can be confident that add is always a key in the dictionary with some value.
A better solution than either your original or my alternative version of it above would be:
capitals.setdefault(add, "?")
This is likely to preform a little better because it's all in one method, so there's no need for the dictionary to need to hash the key twice.
Here's an example to show how the get function works on a dictionary. Let's say your dictionary looks like this:
capitals = {
'MA': 'Boston',
'RI': 'Providence',
'NY': 'Albany'
}
If you use the get function on a valid key, you'll get the value back. For example:
>>> add = 'RI'
>>> capitals.get(add, "?")
'Providence'
If you try the get function on a key that isn't present in the dictionary, then you will get back the missing key value (a '?' in your example).
>>> add = 'TX'
>>> capitals.get(add, "?")
'?'
So if you set capitals[add] = capitals.get(add, "?") it would either create a new key with a value of "?" (if the key doesn't exist) or update an existing key with the same value it already has.
There's other documentation on the web if you search for "python get function". Good luck!
Since you seem to be unable to understand the given response, I'll break it down for you.
The get() method of a dictionary does the following:
Checks the dictionary to see if the dictionary has a key corresponding to the first parameter. Then, it does one of the following:
If there is a key that matches the given one, then it returns the corresponding value.
If there is no matching key, then, if the second parameter is provided, it will return that value.
Now let's look at your question with the following two sample dictionaries:
capitals_1 = {
"UK": "London",
"USA": "Washington DC",
"India": "New Delhi"
}
capitals_2 = {
"Brazil": "Brasilia",
"Australia": "Canberra",
"Russia": "Moscow"
}
add = "India"
For capitals_1, "India" is already a key, so executing the above code will return the value corresponding to "India", which is "New Delhi".
For capitals_2, "India" is not a key, so executing the above code will return the default value specified, which is "?".
With these values obtained, the code then sets the value corresponding to "India" to whatever you got, so if "India" is already a key, then no change, but, if, like the second example, if India is not a key, then the dictionary will have the additional key-value pair of "India":"?".

Most pythonic way of iterating list items into a nested dict

I have a problem and I want to determine whether my approach is sound. Here is the idea:
I would be creating a primary dict called zip_codes, of which respective zipcodes (from a list) were the names of each of the nested dicts. Each would have keys for "members", "offices", "members per office"
It would look like this:
zips {
90219: {
"members": 120,
"offices": 18,
"membersperoffice": 28
},
90220: {
"members": 423,
"offices": 37,
"membersperoffice": 16
}
}
and so on and so forth.
I think I need to build the nested dicts, and then process several lists against conditionals, passing resulting values into the corresponding dicts on the fly (i.e. based on how many times a zip code exists in the list).
Is using nested dictionaries the most pythonic way of doing this? Is it cumbersome? Is there a better way?
Can someone drop me a hint about how to push key values into nested dicts from a loop? I've not been able to find a good resource describing what I'm trying to do (if this is, indeed, the best path).
Thanks.
:edit: a more specific example:
determine how many instances of a zipcode are in list called membersperzip
find corresponding nested dict with same name as zipcode, inside dict called zips
pass value to corresponding key, called "members" (or whatever key)
:edit 2:
MadPhysicist requested I give code examples (I don't even know where to start with this one and I can't find examples. All I've been able to do thus far is:
area_dict = {}
area_dict = dict.fromkeys(all_areas, 0) #make all of the zipscodes keys, add a zero in the first non-key index
dictkeys = list (area_dict.keys())
That gets me a dict with a bunch of zip codes as keys. I've discovered no way to iterate through a list and create nested dicts (yet). Hence the actual question.
Please don't dogpile me and do the usual stack overflow thing. This is not me asking anyone to do my homework. This is merely me asking someone to drop me a HINT.
:edit 3:
Ok. This is convoluted (my fault). Allow me to clarify further:
So, I have an example of what the nested dicts should look like. They'll start out empty, but I need to iterate through one of the zip code lists to create all the nested dicts... inside of zips.
This is a sample of the list that I want to use to create the nested dicts inside of the zips dict:
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
And this is what I want it to look like
zips {
90272: {
"members": ,
"offices": ,
"membersperoffice":
},
90049: {
"members": ,
"offices": ,
"membersperoffice":
}
}
....
etc, etc. ( creating a corresponding nested dict for each zipcode in the list)
After I achieve this, I have to iterate through several more zip code lists... and those would spit out the number of times a zip code appears in a given list, and then find the dict corresponding to the zip code in question, and append that value to the relevant key.
One I figure out the first part, I can figure this second part out on my own.
Thanks again. Sorry for any confusion.
You can do something like this:
all_areas = [90219, 90220]
zips = {zipcode: code_members(zipcode) for zipcode in all_areas}
def code_members(zipcode):
if zipcode == 90219:
return dict(members=120, offices=18, membersperoffice=28)
return dict(members=423, offices=37, membersperoffice=16)
I think I need to build the nested dicts, and then process several
lists against conditionals, passing resulting values into the
corresponding dicts on the fly (i.e. based on how many times a zip
code exists in the list).
Using the above approach, if a zipcode appears multiple times in the all_areas list, the resulting zip dictionary will only contain one instance of the zipcode.
Is using nested dictionaries the most pythonic way of doing this? Is
it cumbersome? Is there a better way?
May I suggest making a simple object that represents the value of each zipcode. Something simple like:
Using dataclass:
#dataclass.dataclass
class ZipProperties(object):
members: int
offices: int
membersperoffice: int
Using named tuple:
ZipProperties = collections.namedtuple('ZipProperties', ['members', 'offices', 'membersperoffice'])
You can then change the code_members function to this:
def code_members(zipcode):
if zipcode == 90219:
return ZipProperties(120, 18, 28)
return ZipProperties(423, 37, 16)
Addressing your concrete example:
determine how many instances of a zipcode are in list called membersperzip
find corresponding nested dict with same name as zipcode, inside dict called zips
pass value to corresponding key, called "members" (or whatever key)
membersperzip: typings.List[Tuple[int, int]] = [(90219, 54)]
for zip, members in membersperzip:
for zipcode, props in zips.items():
if zipcode == zip:
props.members = members
I would suggest you to append it when you have the actual value instead of initializing dictionary with empty values for each key. You have list of keys and I do not see why you want to put all of them to the dictionary without having value in the first place.
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {}
for a_zip in zips:
if a_zip not in zips_dict:
# Initialize proper value here for members etc.
zips_dict[a_zip] = proper_value
If you insist to initialize dict with empty value for each keys, you could use this, which will also iterate through the list anyway but in python comprehension.
zips = [90272, 90049, 90401, 90402, 90403, 90404, 90291, 90292, 90290, 90094, 90066, 90025, 90064, 90073]
zips_dict = {
x:{
"members":None,
"offices":None,
"membersperoffice":None,
} for x in zips
}
Hope this helps

Unable to get each element from variable "coin" to dictionary as key

How do I get dictionary from variable coin which I have define in my code. There are 32 elements in variable coin but I'm getting only one key and value which is TUSD in last line.
import requests
import json
r=requests.get('https://koinex.in/api/ticker')
koinexData=r.json()
koinexprice = koinexData['stats']['inr']
for coin in koinexprice:
print(coin)
coindata={}
coindata["koinex"]={
coin:{
"SellingPrice":koinexprice[coin]["highest_bid"],
"buyingPrice":koinexprice[coin]["lowest_ask"]
}
}
# data.append(coindata)
# print(data)``
# s = json.dumps(coindata)
print(s)
You keep overwriting your coindata dictionary inside the loop, which is why only the last value remains. The second issue with your code is that you keep overriding the coindata['koinex'] dictionary inside the loop. This should be a list not a dictionary because you'll keep adding values to it.
If you move the initialization code outside the loop, you will not have this problem:
coindata = {}
coindata['koinex'] = [] # this should be a list, not a dictionary
for coin in koinexprice:
print(coin)
# Create a temporary dictionary d to hold the data you want
# to add to coindata
d = {coin: {'SellingPrice': koinexprice[coin]['highest_bid'],
'buyingPrice': koinexprice[coin]['lowest_ask']}
}
coindata["koinex"].append(d) # add the new dictionary to the list
print(coindata)

How to save a function to a dictionary entry?

I have this code, Its a slice of my main dictionary I use for my game
GAME_DICT = {
# Player Media, Colors, And Locations
'BLUE': {
'COLOR': g.BLUE,
'PLAYER_IMAGE': m.MEDIA['blue_face'],
'BULLET_IMAGE': m.MEDIA['blue_bullet'],
'LOCAL': 220,
'ABILITY': # Issue
}
Currently, I want to add a function as a value into the dictionary.
Python spits out a syntax error when I try to add a function using def function_name: and when I create a function from outside the dictionary and just save it to an entry it raises an error needing all the args to be filled, which I don't want as I need to fill in specific things as the args when I call this in another file. Any help?
You can store the name of the function in a dictionary without incident.
If you have:
def myfunc(x):
return x * 2
You can also have:
d = {'funcname': myfunc}
You make a named function using the def statement. You can also make a nameless function using the lambda statement.
d = {'funcname' : lambda x:x * 2}
Once you create a function, you can use the name or the lambda reference like any other variable. So...
f = d['funcname']
print('Double is ', f(2))

Categories

Resources