python default dictionary calling key values [duplicate] - python

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!")

Related

How to iterate thorugh JSON/dict in python3? [duplicate]

This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 3 years ago.
I'm sending request to an API using python's requests module and the response is in JSON (can be called dictionary right?)
If I do
for i in response:
print(i)
It would only print the key (the parameter) and not the value, how to get both as output. Thanks.
You can call items to loop over the key/value pairs at the same time.
for key,value in response.items():
print(key, value)
The items method returns an iterator over the key/value pairs of a dictionary.

Python get function [duplicate]

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.

Python "valueless" dictionary [duplicate]

This question already has answers here:
Is there a Python dict without values?
(3 answers)
Closed 2 years ago.
I have a problem where I want to keep track over a large number of values. If I never encountered the value, I'll do action A, otherwise - action B. Naturally, I considered using dictionary to keep track of the values, since the lookup is fast, ~O(1).
However, dictionary is a key-value system, while all I want to take advantage of, is the key.
I can assign a bogus value
"myvalue": None
but I can't help but wonder if there's a more elegant way to go about it.
Thoughts? Ideas?
Thanks!
That's what a set is for:
members = set()
members.add("mykey")
members.add("otherkey")
if "mykey" in members:
. . .
If I were to stick to your dict implementation, I would:
if value in dict:
#Action B
else:
#Action A
dict[value] = 1
so that you wouldn't need to save unseen values in your dict in the first place.
The best suited for your task is frozenset().
The frozenset type is immutable and hashable — its contents cannot be
altered after it is created; it can therefore be used as a dictionary
key or as an element of another set.
members = frozenset([keylist])
if "mykey" in members:
Based on your question, this is the best suited collection form for your task in python.

Possible to convert string to a named variable or alternative? [duplicate]

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)

Dictionary value is different in input and different in output [duplicate]

This question already has answers here:
How to keep keys/values in same order as declared?
(13 answers)
Closed 4 years ago.
I have some error in Python 3 while using dictionaries. The input and output does not match
What you are getting is not an error. Read about dictionaries first: https://www.w3schools.com/python/python_dictionaries.asp
Dictionaries don't work as list. They do not have order. They are hashed data structure that strongly binds keys with value. 5 will always be bound with "five" and 4 will always be bound with "four". If you type dict1[5], you will always get 'five'. In dictionaries, order of arrangement is not important, because python uses complex algorithms to keep key - value bound by hashing, and these algorithms may alter the order of arrangement, but order of arrangement is anyways not important for us in dictionaries.
Never use dictionaries as lists. Dictionaries are collection of key value pairs and you access a value by a key. Lists are like arrays, you access a value by index.

Categories