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"
Related
I know this is relatively a basic question. I am trying to verify if given two sentences are synonym based on the given dictionary.
For example if dictionary is [(movie, film), (john, jack)] then "john likes movie" and "jack likes film" are synonym thus the function below will return true.
I changed each of two strings into the list of words by using lower/strip/split, then I tried to compare both lists by using for and if condition. I can't figure out where I did wrong.
def synonym_checker(synonyms, sentences):
a=sentences[0][0]
b=sentences[0][1]
a.lower()
b.lower()
a.strip()
b.strip()
aw=a.split()
bw=b.split()
import string
at = a.maketrans('','',string.punctuation)
bt = b.maketrans('','',string.punctuation)
ase = [w.translate(at) for w in aw]
bs = [w.translate(bt) for w in bw]
dictionary = dict(synonyms)
this = True
for i in range(0, min(len(ase), len(bs))):
if ase[i] != bs[i]:
if (bs[i] != dictionary[ase[i]]) and bs[i] not in [first for first, second in dictionary.items() if second == ase[i]]:
this = False
if (len(ase) != len(bs)):
this = False
is_synonym = this
print(ase)
print(bs)
return is_synonym # boolean
a = [("film", "movie"), ("revadfsdfs", "ads")]
b = [("I really want to watch that movie, as it had good fdf.", "I really want to watch that film, as it had good fdsaa")]
print(synonym_checker(a, b))
So, your error happened on
dictionary[ase[i]]
Because what you did here is actually
{'film': 'movie', 'revadfsdfs': 'ads'}['movie']
When your "movie" is not a key, but a value.
{'film': 'movie', 'revadfsdfs': 'ads'}
.. ^......... ^.............. ^ ............ ^
key .....value ....... key ....... value
The true problem here in my opinion is, your approach is not correct. Because dictionary is a one-way information, so when you want to check both 'film' to 'movie' and 'movie' to 'film', don't use a dictionary.
It also looks like you are trying to do something unnecessarily complicated for what you are trying to achieve.
a.lower()
b.lower()
a.strip()
b.strip()
Does not do anything to the actual program
The way you named your variables are also very hard to read, so maybe pick a proper name instead.
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
I am trying to make a python program that takes user input text or a file and changes each character into a value and then returns the result.
I have a user string that being read into a list.
I am trying to have a for loop go through that list and check each character against a dictionary key and then return the value in the dictionary. How would i go about doing that?
Thanks
Code so far:
for i in range (0, len(text)):
for j in alphabet.keys():
if text[i].upper() == alphabet.values():
j+=1
print(alphabet.items())
i+=1
for item in list_:
try:
print(d[item])
except KeyError as e:
print("{} not in d".format(e.args[0]))
Without seeing your code, I can't offer anything more relevant
You probably want to use string.maketrans and string.translate
>>> import string
>>> table = string.maketrans('abc', 'xyz')
>>> string.translate('the cat is bad', table)
'the zxt is yxd'
Most of the code below is simply to create the dictionary that translates letters of an input into randomised corresponding values in a dict (i.e. each letter maps to another random letter). Points on your code:
1) range() automatically defaults to starting at 0 so range(0, n) is better just written as range(n)
2) You don't need to use range() at all here. for letter in string will take an input string and go through it, letter by letter. for elephant in string will do the same, each letter is being assigned to the name elephant in turn, so the fact that I chose to use letter instead is simply for readability.
3) Using keys(), values() and items() is not the way to query a dictionary. You have two standard approaches; I could use translation_dict[letter] which will throw KeyError if the value of letter is not a key in the dictionary, or translation_dict.get(letter) which will return None if the key doesn't exist. In the below example, I used get() but also added another parameter ("not in dict") which replaces None as the default value if the letter isn't found as a key.
import string # For setup of example data
import random # For setup of example data
# Just creating the translation dictionary and fake user input
alphabet = list(string.uppercase)
translated = random.sample(alphabet, len(alphabet))
translation_dict = {i: j for i, j in zip(alphabet, translated)}
user_input = 'Hello'
# The loop you're trying
for letter in user_input:
corresponding_value = translation_dict.get(letter.upper(), 'Not in dict')
print(corresponding_value)
I am not sure how to word the question title.
a = "Alpha";
b = "Bravo";
c = "Charlie";
fn = input("What is your first name: ")
for fletter in fn.split():
fl = fletter[0]
The code above gets the first letter entered. The goal is to then get the first letter to possible check in a while loop to see if the value of fl = one of the starting strings. Is that possible to do? Tips on where to begin?
Solution 1 [Using a dictionary]
Also makes things much simpler.
In this case, instead of defining separate variables for each string, you store them in a dictionary. So for example, instead of this:
a = "Alpha"
b = "Bravo"
c = "Charlie"
You would have this:
letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}
This works very similarly to a list, however instead of indexing the dictionary you would reference to separate objects inside a dictionary according to its key. So if the dictionary letterwords is defined as above, you would reference to the string Alpha by calling letterwords["a"]. Therefore, in this case, the code would look something like this:
letterwords = {"a":"Alpha", "b":"Bravo", "c":"Charlie"}
fn = input("Please enter your first name: ")
try:
letterwords[fn[0]]
except KeyError:
print("There is no matching variable with that letter in the database.")
Solution 2 [Using the eval() function]
Not recommended.
This is perfectly possible, with the eval function. However, you should be aware that this is a quite dangerous function to run, as malicious users can use this to control the console. (Especially if you imported os.) However, it should get you over the hump for now. Here's the code:
a = "Alpha"
b = "Bravo"
c = "Charlie"
fl = input("Please enter your first name: ")
try:
compared = eval(fl[0])
except NameError:
print("Your first name's first letter does not match any strings in the database.")
More information on the eval() function here: https://docs.python.org/3/library/functions.html#eval
Hope this helped!
I need to test if the user input is the same as an element of a list, right now I'm doing this:
cars = ("red", "yellow", "blue")
guess = str(input())
if guess == cars[1] or guess == cars[2]:
print("success!")
But I'm working with bigger lists and my if statement is growing a lot with all those checks, is there a way to reference multiple indexes something like:
if guess == cars[1] or cars[2]
or
if guess == cars[1,2,3]
Reading the lists docs I saw that it's impossible to reference more than one index like, I tried above and of course that sends a syntax error.
The simplest way is:
if guess in cars:
...
but if your list was huge, that would be slow. You should then store your list of cars in a set:
cars_set = set(cars)
....
if guess in cars_set:
...
Checking whether something is present is a set is much quicker than checking whether it's in a list (but this only becomes an issue when you have many many items, and you're doing the check several times.)
(Edit: I'm assuming that the omission of cars[0] from the code in the question is an accident. If it isn't, then use cars[1:] instead of cars.)
Use guess in cars to test if guess is equal to an element in cars:
cars = ("red","yellow","blue")
guess = str(input())
if guess in cars:
print ("success!")
Use in:
if guess in cars:
print( 'success!' )
See also the possible operations on sequence type as documented in the official documentation.
#Sean Hobbs:
First you'd have to assign a value to the variable index.
index = 0
You might want to use while True to create the infinite loop, so your code would be like this:
while True:
champ = input("Guess a champion: ")
champ = str(champ)
found_champ = False
for i in listC:
if champ == i:
found_champ = True
if found_champ:
print("Correct")
else:
print("Incorrect")