Have a query on Dictionary Topic in Python - python

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}"

Related

Using a key taken from an input and using it to recall a value

The project is based on a cashier. When an input is accepted, it gets stored. I have used this to determine whether an item is in the dictionary or not.
I am currently stuck on how to implement the input as a key to recall the corresponding value in a defined dictionary.
Is there any way to do this using the tools I've used, or is a more complicated function required? My code is underneath, and the very last line seems to be the problem. Thanks.
my_dictionary = {"Chips", 1}
#Taking order
order = input("What do you want? \n")
#Recalling order
if order in my_dictionary:
print(f"Okay you want {order}")
else:
print("We dont have that please leave")
exit()
#Gving price
print(my_dictionary["order"])
Below is the code I have written that checks if the order the user inputs is:
In your dictionary.
In stock.
Python is case sensitive so I have added the .title() method to the user input to convert the string to title case. This is because the 'Chips' in your dictionary is also in title case.
my_dictionary = {
"Chips" : 1
}
order = input("What do you want?\n").title()
if order in my_dictionary:
if my_dictionary[order] == 0:
print("We don't have that, please leave.")
else:
print(f"Okay you want, {order}")
Hopefully this helps :)
remove the " " around order like: my_dictionary[order] in your last print() function.
I've opted to use this code for the time being, having solved the issue:
my_dictionary = {"chips", 1}
order = input("What do you want?\n").lower()
if order in my_dictionary:
print(f"Ok you want {order}")
else:
print("We dont have that, leave")

how do i match if value match my dictionary in python

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

python automatically change a variable from list to string inside a for loop

Python automatically changes a variable from list to str inside a for loop so I got an error when I append to the list. Why does this happen?
By looking at your provided question and the output, I think that you are basically trying to swap the dictionary values of the given one.
So, the code for that is :
def func(dct):
new_dct = {}
for key, values in dct.items():
for value in values:
if value in new_dct:
new_dct[value].append(key)
else:
new_dct[value]=[key]
return (new_dct)
dct = {'local': ['admin', 'userA'],
'public': ['admin', 'userB'],
'administrator': ['admin']}
print(func(dct))
I guess this should work for you!
Considering Upvoting if found helpful!
Just change line 14 to
ug = [groups,].

Dynamically building a dictionary based on variables

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.

Retrieve keys using values from a dictionary

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

Categories

Resources