This question already has answers here:
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 3 years ago.
monthConversions={
"Jan":"January", #key:value
"Feb":'February', #make sure keys are unique
'Mar':'March', #can also use integers
'Apr':"April",
'May':'May',
'Jun':'June',
}
print(monthConversions['Jan']) #gives value associated with the key
print(monthConversions.get('Luv','not a valid key'))
Hi, I am currently learning python through freebootcamp on youtube, and the person mentioned we can use the get function to pass in a value for a key that is not in the dictionary. I kind of understand that, but I fail to see what the use of this would be. I thought it would add Luv in when I put in
print(monthConversions['Luv'])
but it instead gives a error. What would be the purpose of the get function in this situation anyway? It feels like extra work and I don't get how it would be useful. Any explanations would be greatly appreciated, thank you.
It does not change the dict. The second argument is simply what get() returns when key is not found. If you don't specify it, it will simply return None.
Related
This question already has answers here:
What does "list comprehension" and similar mean? How does it work and how can I use it?
(5 answers)
Closed 1 year ago.
I don't know Python super well but I know it well enough that I'm trying to translate some Python code to Lua. But I can't figure out what this code is supposed to do.
var_declarations = [
VarDecl(var_node, type_node)
for var_node in var_nodes
]
VarDecl is a class, and var_nodes is a list. Full code is here.
That's called a "list comprehension". It is exactly the same as:
var_declarations = []
for var_node in var_nodes:
var_declarations.append( VarDecl(var_node, type_node) )
It just builds a new list with the result of calling VarDecl one at a time.
This is a list comprehension syntax. Looking at the code snippet that you referred to, it is instantiating the VarDecl class for each var_node in var_nodes list(array) and creating a new list called var_declarations.
This question already has answers here:
How do I create variable variables?
(17 answers)
How can I create multiple variables from a list of strings? [duplicate]
(2 answers)
generating variable names on fly in python [duplicate]
(6 answers)
Closed 3 years ago.
I have a ticker and I want to check a specific list of tickers to see if the ticker is found. If it is found, it will replace it.
The new tickers come from another data source and therefore do not know which specific list of tickers to check. In order to find that list, I can pass the lists name as a string but upon iterating the code (naturally) recognizes this as string as opposed to a list to iterate.
Is there a way to have the code/function recognize that the string is actually a specific list to be checked? In reading other questions, I know this may not be possible...in that case what is an alternative?
list_1=['A','B']
list_2=['C','D']
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list):
for ticker in list:
if new_ticker in list:
return
else:
list.append(new_ticker)
list.remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
You key the needed lists by name in a dictionary:
ticker_directory = {
"list_1": list_1,
"list_2": list_2
}
Now you can accept the name and get the desired list as ticker_directory[assigned_list].
list_1=['A','B']
list_2=['C','D']
lists = {
'list_1':list_1,
'list_2':list_2
}
old_ticker='A'
new_ticker='E'
assigned_list='list_1'
def replace_ticker(old_ticker,new_ticker,list_name):
if old_ticker not in lists[list_name]:
return
else:
lists[list_name].append(new_ticker)
lists[list_name].remove(old_ticker)
replace_ticker(old_ticker,new_ticker,assigned_list)
print(lists[assigned_list])
This is the complete program from what i perceived.
#prune already answered this, I have just given the whole solution
There are at least two possibilities:
1 As noted in comments kind of overkill but possible:
Use eval() to evaluate string as python expressions more in the link:
https://thepythonguru.com/python-builtin-functions/eval/
For example:
list_name = 'list_1'
eval('{}.append(new_ticker)'.format(list_name))
2 Second
Using locals() a dictionary of locally scoped variables similiar to the other answers but without the need of creating the dict by hand which also requires the knowledge of all variables names.
list_name = 'list_1'
locals()[list_name].append(new_ticker)
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I don't get KeyError when I use a constant (whose value is the same as the variable) for [key].
For example:
self._answer= input("Which appointment would you like to delete?")
self._useless= self._book.pop(self._answer)
Gives a key error when self._answer= 1001, however:
self._useless= self._book.pop(1001)
works as desired. Any ideas how I can resolve this issue?
Edit: As #user2357112 suggested below, the following piece of code worked: def deleteAppointment(self):
self._answer= int(input("Which appointment would you like to delete?"))
del self._book[self._answer]
However, after redoing the entire project I no longer ran into the problem above (i.e. using [dictionary].pop([key]) no longer produced a KeyError). Therefore, if you are getting this error there is likely a bug in your code.
input on Python 3 returns a string, and '1001' != 1001. If your key is the int 1001, you will need to convert the input to an int:
self._answer= int(input("Which appointment would you like to delete?"))
As an aside, the name self._useless indicates that you might not care about the result of the pop operation. If you just want to remove the entry from the dict, you can use del:
del self._book[self._answer]
or you could ignore the return value of pop and not assign it to anything:
self._book.pop(self._answer)
This question already has answers here:
Is there a difference between using a dict literal and a dict constructor?
(12 answers)
Closed 7 years ago.
Consider these two statements, which serve the same purpose:
tel = {'sape': 4139, 'jack': 4098}
and
tel = dict([('sape', 4139), ('jack', 4098)])
Why use "dict()" at all?
I am sure there is a reason, i just want to know it.
The reason for the existence of dict(...) is that all classes need to have a constructor. Furthermore, it may be helpful if the constructor is able to take in data in a different format.
In your example use case, there is no benefit in using dict, because you can control the format the data is in. But consider if you have the data already as pairs in a list, the dict constructor may be useful. This can happen e.g. when reading lines from a file.
map(dict,[[(1,2)]])
[{1: 2}]
map({},[[(1,2)]])
TypeError: 'dict' object is not callable
This question already has answers here:
Python Dictionary DataStructure which method d[] or d.get()?
(5 answers)
Closed 8 years ago.
I have written a bit of code using
setting value
dic["key"] = "someval"
and fetching it the same way
print dic["key"]
then I discovered that an alternative way to fetch a dictionary value is to use
print dic.get("key")
I want all my code to use the same method, so should I rewrite all using dic.get("key") ?
If you have a flat dictionary and you want to add or modify a key/value pair, than the best way is to use a simple assignment:
h[key] = value
The get method is useful when you want to get a value from a dictionary for existing keys or use a default value for non-existing keys:
print h.get(key, "Does not exist!")