I'm super new to python so i don't know anything even the basics of basics function so could anyone tell me how do i match value to my dictionary and where did i do wrong
#dictionary
id = {"2":"30", "3":"40"}
#json display from web
messages: {"id":2,"class":0,"type":1,"member":"N"}
if messages['id'] == id: # << this part i think i'm doing it wrong too because it prints error`
print ('the new id value from dictionary') # << what do i put in here`
else:
print ('error')
Use if str(messages['id']) in id instead of if messages['id'] == id
to check if a values is a key in a dict you can do it like this:
if messages['id'] in id:
but it will not work right away in your case.
The values in the json data are integers so you need to convert them to match the dict.
you will end up with this
if str(messages['id']) in id:
full code:
id = {"2": "30", "3": "40"}
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id:
print(id[str(messages['id'])])
else:
id[str(messages['id'])] = '50'
The error occurs because you need to use an = to assign variables:
messages = {"id":2,"class":0,"type":1,"member":"N"}
instead of
messages: {"id":2,"class":0,"type":1,"member":"N"}
Concerning what you want to achieve, you are trying to access a dictionary value by using a default value ("error") in case the key doesn't exist. You can use dict.get for that, rather than if-else:
#dictionary
id_dict = {"2":"30", "3":"40"}
#json display from web
messages = {"id":2,"class":0,"type":1,"member":"N"}
print(id_dict.get(messages['id'], "error"))
Caveats:
Don't use id as a variable name, as it is a Python built-in keyword.
If the id_dict has string keys, you also need to use strings to access it, i.e. messages = {"id":2 ... will not give you the value "30" for id_dict = {"2":"30", "3":"40"}.
You need to convert the value to check to string in order to perform a valid comparison. Also, you should not use Python keywords as name variables to avoid additional issues:
id_dict = {"2":"30", "3":"40"}
#Use = to assign variables, not :
messages = {"id":2,"class":0,"type":1,"member":"N"}
if str(messages['id']) in id_dict:
print ('the new id value from dictionary')
else:
print ('error')
Output:
the new id value from dictionary
Related
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".
hey I have been trying to get this value from one dictionary and use it as a key with another dictionary. and I get keyError
userID = some input lets say 364853
BALANCE = {540997: 10500, 266732: 50000}
ACCOUNTS = {364853: 540997, 266732: 540922}
and I'm trying to print:
print(ACCOUNTS[BALANCE[userId]])
and i get keyError( 364853 )
You have your references backwards. Let's do this in order. You have a userID; you need to get the account number. First, if this is the straight user input -- a string, rather than the int you show in your code and error message -- then you must convert it. Then you look it up in ACCOUNTS:
acct_no = ACCOUNTS[int(userID)]
Now, you use the account number to get the balance:
user_bal = BALANCE[acct_no]
In this statement, using simple algebraic substitution:
user_bal = BALANCE[ACCOUNTS[userID]]
See how that works? In English, this reads as "I want the balance of the account of the userID".
I am trying to build a dictionary based on a larger input of text. From this input, I will create nested dictionaries which will need to be updated as the program runs. The structure ideally looks like this:
nodes = {}
node_name: {
inc_name: inc_capacity,
inc_name: inc_capacity,
inc_name: inc_capacity,
}
Because of the nature of this input, I would like to use variables to dynamically create dictionary keys (or access them if they already exist). But I get KeyError if the key doesn't already exist. I assume I could do a try/except, but was wondering if there was a 'cleaner' way to do this in python. The next best solution I found is illustrated below:
test_dict = {}
inc_color = 'light blue'
inc_cap = 2
test_dict[f'{inc_color}'] = inc_cap
# test_dict returns >>> {'light blue': 2}
Try this code, for Large Scale input. For example file input
Lemme give you an example for what I am aiming for, and I think, this what you want.
File.txt
Person1: 115.5
Person2: 128.87
Person3: 827.43
Person4:'18.9
Numerical Validation Function
def is_number(a):
try:
float (a)
except ValueError:
return False
else:
return True
Code for dictionary File.txt
adict = {}
with open("File.txt") as data:
adict = {line[:line.index(':')]: line[line.index(':')+1: ].strip(' \n') for line in data.readlines() if is_number(line[line.index(':')+1: ].strip('\n')) == True}
print(adict)
Output
{'Person1': '115.5', 'Person2': '128.87', 'Person3': '827.43'}
For more explanation, please follow this issue solution How to fix the errors in my code for making a dictionary from a file
As already mentioned in the comments sections, you can use setdefault.
Here's how I will implement it.
Assume I want to add values to dict : node_name and I have the keys and values in two lists. Keys are in inc_names and values are in inc_ccity. Then I will use the below code to load them. Note that inc_name2 key exists twice in the key list. So the second occurrence of it will be ignored from entry into the dictionary.
node_name = {}
inc_names = ['inc_name1','inc_name2','inc_name3','inc_name2']
inc_ccity = ['inc_capacity1','inc_capacity2','inc_capacity3','inc_capacity4']
for i,names in enumerate(inc_names):
node = node_name.setdefault(names, inc_ccity[i])
if node != inc_ccity[i]:
print ('Key=',names,'already exists with value',node, '. New value=', inc_ccity[i], 'skipped')
print ('\nThe final list of values in the dict node_name are :')
print (node_name)
The output of this will be:
Key= inc_name2 already exists with value inc_capacity2 . New value= inc_capacity4 skipped
The final list of values in the dict node_name are :
{'inc_name1': 'inc_capacity1', 'inc_name2': 'inc_capacity2', 'inc_name3': 'inc_capacity3'}
This way you can add values into a dictionary using variables.
I am not able to proceed in a program I was practicing in Python. It is about Dictionaries in Python.
The Question is : Write a python program to check whether the given key is present, if present print the value , else add a new key and value.
My solution:
class Pro2:
def check(self):
dict = {}
a=""
b=""
c=""
d=""
for x in range(5):
a=(input("Enter key: "))
b=(input("Enter value: "))
dict[f"{a}":f"{b}"]
c=input("Enter a key which is to be checked: ")
if (dict.__contains__(c)):
print(dict[c])
else:
d=input("Enter the value to be added: ")
dict[f"{c}":f"{d}"]
Now the problem occurring is that, the accepted input is not being appended in the respective Dictionary in the 'for' loop.
Can anybody please help me. Suggestions for better solutions are also accepted.
Thank You in Advance!
You are assigning the dict values wrong
Error:
dict[f"{c}":f"{d}"]
so dict[#add key here#] = #your value
also if you do : in a list([:]) it is used to split the list and values to left and right of : should be indexes(int) or empty ( )
Correction:
dict = {}
a = "hello"
b = "world"
dict[f"{a}"]=f"{b}"
Basically I am trying to find a way to get the key of a value from a dictionary by searching the value.
people = {
"Sarah" : "36",
"David" : "42",
"Ricky" : "13"
}
user_input = ('Enter the age of the individual") #The user enters the
#value
key_to_output = (...) #The variable that would contain the key value
print(key_to_output)
For example in the dictionary above if the user enters "36", they would be returned have "Sarah" returned. The dictionary I am using will never have a overlapping values so don't worry about any issues that would cause.
Also, because my python knowledge isn't very advanced it would be much appreciated if the responses were kept quite amateur so I can understand them properly.
You can invert the dictionary as so -
people_inv = {v:k for k,v in people.items()}
Now say your user inputted 36,
user_input = "36"
people_inv[user_input] # this will give Sarah
If the values are not unique like in the example below, you can do this -
people = {"Sarah":36, "Ricky":36, "Pankaj":28}
people_inv= {}
for k,v in people.items():
people_inv.setdefault(v, []).append(k)
people_inv["36"]
Output
['Sarah', 'Ricky']
The easyest way would be to itterate over the values like this.
def find_key(value, people):
for name in people:
if people[name] == value:
return name
If you are trying to get mutliple keys I would try:
def find_key(value, people):
names = []
for name in people:
if people[name] == value:
names.append(name)
return names