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
Related
I'm trying to build a function that checks and returns an entry that matches its records.
Only issue is that there are 2 values (album_title and songs) in the dictionaries and I don't know how to loop through the 2nd value.
def make_album(artist, album_title, songs = None):
A = {
'artist1': 'album1', 'songs': '1'
}
B = {
'artist2': 'album2', 'songs': '2'
}
C = {
'artist3': 'album3', 'songs': '3'
}
dicts = [A, B, C]
for dictionary in dicts:
for key, value in dictionary.items():
if key == artist and value == album_title:
print(dictionary)
make_album('artist2', 'album2')
Any help is appreciated.
Thanks!
Seems like each dict here is really a pseudo-object describing describing an album. You don't want to iterate it at all, just perform lookups as needed.
So instead of:
for key, value in dictionary.items():
if key == artist and value == album_title:
print(dictionary)
you'd want something like:
if dictionary.get(artist, None) == album_title:
print(dictionary)
or roughly equivalently:
if artist in dictionary and dictionary[artist] == album_title:
print(dictionary)
Both of those do the same basic thing:
Check if the provided artist is a key in the dict, and
Verify that the album title associated with it matches the provided album_title
If both checks pass, you've found the album you were looking for. No need to loop at all, you just use the cheap membership tests and lookup-by-key features of dict to check the specific data you're interested in.
Once you know you've got a hit, you can just look up dictionary['songs'] to get the value associated with that key.
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
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}"
I have started learning python. In this code, I am trying to print the Birthdate of the inputted user along with his/her name. I am using a dictionary to achieve this functionality. Below is my code snippet
n=input("Enter Name: ")
def birth():
dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}
if dict1["name"]==n:
print(dict1["name"]+"'s birth was on " +dict1["birthdate"])
else:
print("Not in database")
birth()
My expected output should look like this on inputting X:
X's birthdate was on 16-June-1989
But I am getting below error, I tried an online search, but I wanted to understand what I am missing here. I am sure I will be getting many comments. But I am also sure that many will provide constructively and learning suggestions.
File "main.py", line 8, in <module>
birth()
File "main.py", line 3, in birth
dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}
TypeError: unhashable type: 'dict'
You are getting the error because dictionary variable dict1 can't parse its own elements,so you need to create an variable/object which can parse the elements of the dictionary which is done by parse variable p
n=input("Enter name: ")
def birth(n):
dict1=[{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}]
for p in dict1:
if p["name"]==n:
print(p["name"]+"'s birth was on " +p["birthdate"])
break;
else:
print("Not in database")
break;
birth(n)
The way you defined your dict1 is incorrect. It should be like this:
In [1131]: def birth(n):
...: #dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}
...: dict1=[{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}]
...: for d in dict1:
...: if d["name"]==n:
...: print(d["name"]+"'s birth was on " +d["birthdate"])
...: else:
...: print("Not in database")
...:
In [1132]: birth(n)
X's birth was on 16-June-1989
Also, it would make more sense if you pass the user input n as a parameter to your function birth. Then call the method like birth(n).
Otherwise, the method is tightly coupled with the variable named n.
That's because you have a wrong dict initialization.
In python 3+ curly brackets are used not only for dict literal but and for set literal. You can get more info in this question.
For example:
# that will be a dict:
d = {"name": "My name", "birthdate": "16-June-1989"}
# and that will be a set:
d = {"name", "birthdate"}
# your line 3 has set initialization, which contains 2 dicts of user info:
dict1={{"name":"X","birthdate":"16-June-1989"},{"name":"Y","birthdate":"23-08-1990"}}
One more problem that in Python sets must contain only hashable elements and dict is not hashable. Here is the explanation.
So you should change your dict1 variable type to list or tuple. If you need more info about the difference between lists, sets and tuples here is a link to python documentation about data structures.
And also your function will print something for every entry in your database. I think that you need only 1 print after function execution.
So your function should look like that:
def birth(name):
database = [{"name": "X", "birthdate": "16-June-1989"},
{"name": "Y", "birthdate": "23-08-1990"}]
found = False
for entry in database:
if entry["name"] == name:
print(entry["name"] + "'s birth was on " + entry["birthdate"])
found = True
break
if not found:
print("Not in database")
birth('X')
# Will print: X's birth was on 16-June-1989
birth('My name is')
# Will print: Not in database
Make sure that your dictionary definition is correct. It should have the form:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
You can not use a dictionary as a key in a dictionary.
From the Python documentation:
dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().