Python dictionnaries have keys and values accessed using those keys.
You can access the keys as follows, your dict key will be stored in the key variable:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
print(key)
This will print:
a
b
You can then do any comparisons you want:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
if key == "a":
return True
else:
return False
which can be improved to:
my_dict = {"a" : 1, "b" : 2}
print("a" in my_dict.keys())
You can then access the values for each key in your dict as follows:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
print(my_dict[key])
This will print:
1
2
I suggest you read more about dictionaries from the official Python documentation: https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries
Answer from Adam J on Stack OverflowPython dictionnaries have keys and values accessed using those keys.
You can access the keys as follows, your dict key will be stored in the key variable:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
print(key)
This will print:
a
b
You can then do any comparisons you want:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
if key == "a":
return True
else:
return False
which can be improved to:
my_dict = {"a" : 1, "b" : 2}
print("a" in my_dict.keys())
You can then access the values for each key in your dict as follows:
my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
print(my_dict[key])
This will print:
1
2
I suggest you read more about dictionaries from the official Python documentation: https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries
result = True if "a" in dict.keys() else False
return result
For the example in your question, result will be True.
If you want to go through each keys, indexes won't help because dictionaries in Python cannot be instead. You can do the following instead:
for key in dict.keys():
#do something with key
python - how to compare a key of the dictionary with a string character - Stack Overflow
python - How do I compare a string with a dictionary element? - Stack Overflow
Comparing Python dictionary values if one dictionary has values equal, or more than the another
python - Comparing two dictionaries and checking how many (key, value) pairs are equal - Stack Overflow
Videos
Looks like you're thinking about this strangely. All you need to do is check if the letter is in your score dict, and if it is, to add that number to your total.
def compare(word):
res = 0
for letter in word:
if letter in score:
res += score[letter]
return res
However there's an easier way to do this. Since you're just using res as an accumulator, you can add score[letter] if it exists or 0 if it doesn't. This is easy using the dict.get method.
def compare(word):
res = 0
for letter in word:
res += score.get(letter, 0)
# dict.get(key, defaultvalue)
return res
In fact you can even make it into an ugly lambda.
compare = lambda word: sum([scores.get(letter,0) for letter in word])
score = {"a": 1, ...}
def compare(word):
res = 0
for letter in word:
if letter in score:
res += score[letter]
return res
That's probably what you want. You can even omit if letter in score if you're sure all your letters will exist in score. You don't really need to compare anything.
I think your problem is that a is a variable instead bing the string 'a'
this work
o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]
min_node = 'a'
def f():
for i, elem in enumerate(o_list):
if min_node == o_list[i]['name']:
return min_node
else:
return 'error in retrieving min F'
print f()
however it would be more elegant to do the following
o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]
min_node = 'a'
def f():
for elem in o_list:
if min_node == elem["name"]:
return min_node
else:
return 'error in retrieving min F'
print f()
Not sure why you are using enumerate; the below snippet builds a list called names and simply uses the in clause to check whether a name is in such list:
In [2]: o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]
In [3]: names = [item.get('name') for item in o_list] # build list
In [4]: names # show list contents
Out[4]: ['a', 'b', 'c']
In [5]: 'a' in names
Out[5]: True
In [6]: 'z' in names
Out[6]: False
Here is the scenario:
dict1 = { A : 1 , B : 3 , C: 0 }
dict2 = {C : 1, D : 2 , A : 1, B : 3 }
dict3 = {E : 1, B : 3, A : 1, C : 0}
Assuming dict1 is the baseline that subsequent dictionaries (dict2, dict3) need to be compared against, I am thinking about codes that check if dict 2 >= dict1 or dict 3 >= dict1:
-
I understand dictionary is unordered, so does that mean that the dictionary can be compared without sort method?
-
does extra elements in dict2 and dict3 affect the comparison operation, should my code factor extra elements?
-
i think the best way would be something similar to cmp() in Python2, is any function similar to cmp() for dictionary? I don't intend to import any outside library, but okay with builtin modules.
I would like to some pointers to solve the question. Thank you for the help in advance!
If you want to know how many values match in both the dictionaries, you should have said that :)
Maybe something like this:
shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(len(shared_items))
dict1 == dict2
From python docs:
The following examples all return a dictionary equal to
{"one": 1, "two": 2, "three": 3}:>>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True
Providing keyword arguments as in the first example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.
Valid for python2 and python3.
You need to iterate over the keys in crucial and compare each one against the dishes keys. So a directly modified version of your code.
for key in crucial.keys():
if key in dishes.keys():
print(dishes[key])
It could be better stated as (no need to specify .keys):
for key in crucial:
if key in dishes:
print(dishes[key])
If you're using Python 3, the keys method of dictionaries follows the set interface. That means you can do an intersection of the keys of the two dictionaries using the & operator.
for key in crucial.keys() & dishes.keys():
print(dishes[key])
Or if you need a list of the values:
result = [dishes[key] for key in crucial.keys() & dishes.keys()]
In Python 2 you could manage the same thing by explicitly creating sets (perhaps from the iterkeys generator), but probably it would be better to simply do a loop over the keys, like several of the other answer suggest.
Here's a variation on the loop that I don't think I've seen anyone else do. The outer loop gets both the keys and values from the dishes dict, so you don't need to separately look up the value by key.
for key, value in dishes.iteritems(): # use items() in Python 3
if key in crucial:
print value
Try:
mydict = {"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
mystring = "I love simplicity"
if any((word in mystring) for word in mydict["value for money"]):
print("Found one.")
d={"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
s="I love simplicity"
for w in s.split(' '):
if w in d["value for money"]:
print (w," is in value for money")
Hi All,
I am working on something and I need to compare the values of a list to keys in a dictionary to find if they are they same. Then, if they are the same, print the value of that key. What is the best way to go about this? I tried:
alpha = {
'a' : 1
'b' : 2
'c' : 3
}
lst = [ 'a', 'b', 'c']
for i in alpha:
if i == alpha[i]:
print alpha[i]
else:
return FalseEvery time I ran the code it failed. Can someone explain why this doesn't work and how to fix it?