python dictionary checking with key - python

I want to check whether my key is equal to the input:
topics = c.classify("what about ")
a = topics.keys()
if a == "resources":
print("yes")
But a is stored as dict_keys(['resource"])
I want a to be just "resources".
can anyone help me on this,please?

You should first convert the keys into regular python list and then iterate in it (You probably can do it without converting, but I think it is more simple to find).
topics = c.classify("what about ")
a = list(topics.keys())
for key in a:
if key == "resources":
print("yes")
Don't forget a dict can have multiple values.
As #rob-bricheno said, you can do it simpler with in operator. This operator will loop through the list and if the element you've specified is in it, return True, otherwise it will return False value. So you can do it with this simplified code:
topics = c.classify("what about ")
a = list(topics.keys())
if "resources" in a:
print("yes")
When resources is in the a list, if condition is True, so the print will call. When it is not in the a, print will skip.

You can use in. When you use this with a dictionary, it checks if the value you've specified is a key in the dictionary.
topics = c.classify("what about ")
if "resources" in topics:
print("yes")
This is the fastest and most standard way to do this. Read here for more Python dictionary keys. "In" complexity

Related

Python Retrieve value from dict using variable as key [duplicate]

This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Closed 2 years ago.
Apologies if this is really simple, but I can't seem to get it going.
My application is working with nested dicts. For example: -
test = {
"alpha": "first",
"beta": {
"mid": {
"message": "winner winner"
}
},
"omega": "last"
}
Now I need to be able retrieve values out of that dict using variable the value of which is being dynamically constructed based on myriad other factors. So essentially I'm trying to put together a way to generate the key that I need depending on variable factors.
For example if I get back from one function "beta", from another, "mid" and from another "message", the best I can think to do is assemble a string which looks like the key path.
So for example:
current = '["beta"]["mid"]["message"]'
How can I use current to get back the "winner winner" string?
I have tried things like:-
v = '"[beta"]["mid"]"message]"'
print(test[v])
But just hitting Key errors.
Must be an easy way to get values based on calculated keys. Would appreciate a shove in the right direction.
[Question text updated]
Yes, I know I can do:
val = test['beta']['mid']['message']
And get back the value, I'm stuck on how to use the generated string as the the key path. Apologies for not being clear enough.
import re
t = '["beta"]["mid"]["message"]'
val = None
for i in re.findall(r'"([^"]+)"', t):
if(val == None):
val = test.get(i)
else:
val = val.get(i)
print(val)
or,
from functools import reduce
import operator
import re
t = '["beta"]["mid"]["message"]'
reduce(operator.getitem, re.findall(r'"([^"]+)"', t), test)
winner winner
Store the three keys as three different variables rather than as a string:
key_one = 'beta'
key_two = 'mid'
key_three = 'message'
v = test[key_one][key_two][key_three]
If you already have the keys in the string format you describe, then do some string splitting to produce three variables like the above. You don't want to eval the code as it creates a security risk.
current = '["beta"]["mid"]["message"]'
keys = [w.strip('[]"') for w in current.split('"]["')]
test[keys[0]][keys[1]][keys[2]]
# or
# key_one = keys[0]
# key_two = keys[1]
# key_three = keys[2]
# v = test[key_one][key_two][key_three]
This should do it:
v = test['beta']['mid']['message']
print(v)
Note: The issue is you're indexing the dictionary with a string in your example, not a set of keys.

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.

Have a query on Dictionary Topic in 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}"

Existence test in 3 level of nested dictionary

I have the following dictionary:
In [32]: mydict
Out[32]:
{'Foo': {'DendriticCells': {'LV.ip': [15.14,1.003],
'SP.ip': [16.0282,3.001]},
'Macrophages': {'LV.ip': [32.137260000000005],
'SP.ip': [34.020810000000004]},
'NKCells': {'LV.ip': [4.89852], 'SP.ip': [5.18562]}}}
Given a string that correspond to key level 3, what I want to do to have a construct
to check the existence in the dictionary based on choices below.
What's the way to do it. I tried this but failed.
choice1 = "LV.ip"
choice2 = "KK.ip"
choices = [choice1,choice2]
celltypes = ["DendriticCells", "Macrophages", "NKCells"]
for ch in choices:
for ct in celltypes:
if mydict["Foo"][ct][choices]:
print "THERE\n"
else:
print "Not there\n"
Your if statement should use ch, not choices
You should break up the test in that if; for example, make sure that mydict["Foo"][ct] exists before trying to see if it contains anything.
Consider using dict.get.
You might want to do something like mydict.get("Foo", {}).get(ct, {}).get(ch):. Essentially get a default empty dict that will default onto nothing towards the end.
Alternatively, use in to verify the keys. You might have something like
if ct in mydict['foo'] and ch in mydict['foo'][ct]:
Which should not fail due to lazy evaluation in Python.
You can use any function and in operator to check if the key exists in the dictionary or not.
for choice in choices:
for key in my_dict:
if any(choice in my_dict[key][key1] for key1 in my_dict[key]):
print "{} is there".format(choice)
Output
LV.ip is there
You are using the wrong variable name
choice1 = "LV.ip"
choice2 = "KK.ip"
choices = [choice1,choice2]
celltypes = ["DendriticCells", "Macrophages", "NKCells"]
for ch in choices:
for ct in celltypes:
if mydict["Foo"][ct][ch]: // change choices to ch
print "THERE\n"
else:
print "Not there\n"

Search for a key in a nested Python dictionary

I have some Python dictionaries like this:
A = {id: {idnumber: condition},....
e.g.
A = {1: {11 : 567.54}, 2: {14 : 123.13}, .....
I need to search if the dictionary has any idnumber == 11 and calculate something with the condition. But if in the entire dictionary doesn't have any idnumber == 11, I need to continue with the next dictionary.
This is my try:
for id, idnumber in A.iteritems():
if 11 in idnumber.keys():
calculate = ......
else:
break
You're close.
idnum = 11
# The loop and 'if' are good
# You just had the 'break' in the wrong place
for id, idnumber in A.iteritems():
if idnum in idnumber.keys(): # you can skip '.keys()', it's the default
calculate = some_function_of(idnumber[idnum])
break # if we find it we're done looking - leave the loop
# otherwise we continue to the next dictionary
else:
# this is the for loop's 'else' clause
# if we don't find it at all, we end up here
# because we never broke out of the loop
calculate = your_default_value
# or whatever you want to do if you don't find it
If you need to know how many 11s there are as keys in the inner dicts, you can:
idnum = 11
print sum(idnum in idnumber for idnumber in A.itervalues())
This works because a key can only be in each dict once so you just have to test if the key exits. in returns True or False which are equal to 1 and 0, so the sum is the number of occurences of idnum.
dpath to the rescue.
http://github.com/akesterson/dpath-python
dpath lets you search by globs, which will get you what you want.
$ easy_install dpath
>>> for (path, value) in dpath.util.search(MY_DICT, '*/11', yielded=True):
>>> ... # 'value' will contain your condition; now do something with it.
It will iterate out all of the conditions in the dictionary, so no special looping constructs required.
See also
how do i traverse nested dictionaries (python)?
How to do this - python dictionary traverse and search
Access nested dictionary items via a list of keys?
Find all occurrences of a key in nested python dictionaries and lists
Traverse a nested dictionary and get the path in Python?
Find all the keys and keys of the keys in a nested dictionary
Searching for keys in a nested dictionary
Python: Updating a value in a deeply nested dictionary
Is there a query language for JSON?
Chained, nested dict() get calls in python

Categories

Resources