Searching for a key inside dictionary tuple keys in Python - python

Whilst trying to run the following code:
temp3 = {
('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD','EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP'):'EURIBOR_EUR_1Y'
}
print (temp3.get('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD'))
Output:
None
Expected:
EURIBOR_EUR_1Y

You're expecting the get function to unpack the key values and search inside the tuples; it doesn't work that way.
The correct way is to use the key that you used to create the dict.
Example:
temp3 = {
('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD',
'EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP'):'EURIBOR_EUR_1Y'
}
print(temp3.get(('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD',
'EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP')))
Which will output the key; to get all values that have the key that matches you can use the following:
def key_search(needle, haystack):
matches = []
for key, value in haystack.items():
if type(key) in [list, tuple, dict] and needle in key:
matches.append(value)
elif needle == key:
matches.append(value)
return matches
data = {
(1, 2, 3): 'heyyy',
(2, 1): 'heyyy there'
}
print(key_search(1, data))
Output
['heyyy there', 'heyyy']
Where needle is the key you're looking for, and the haystack is your data.

Actually the correct key is ('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD','EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP')
So if you'll try:
print(temp3.get(('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD','EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP')))
You'll get:
EURIBOR_EUR_1Y

You are not using the complete key for the dictionary.
Try with complete key
(temp3.get('EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD','EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP'))
'EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-GBP'

This is what you are looking
print(temp3.get([i for i in temp3 if 'EUR-EURIBOR-1Y-SWAPTION-PHYSICAL-ANNUAL-BOND-QUANTO-USD' in i][0]))
Output:
EURIBOR_EUR_1Y

Related

converting a string to dot notation to access value in nested list in python

items={
"fruits":
{
"summerFruits":
{
"Mangoes":5,
"melon":2
}
}
}
i converted it to attribute
itemConverted = AttrDict(items)
now i know i can access this by
itemConverted.fruits.summerFruits.Mangoes
but the problem is , i am taking inputs from console as a string so
it will be like
wanted="fruits.summerFruits.Mangoes"
i am trying to get it by
itemConverted.wanted
but it is not working , any suggestions
Get the dictionary keys from the string and then use the dictionary items to recover the value.
items={"fruits":{"summerFruits": {"Mangoes":5, "melon":2}}}
def get_val_from_str(string, dct):
keys = string.split('.')
v = dct
for key in keys:
v = v[key]
return v
console_input = "fruits.summerFruits.Mangoes"
get_val_from_str(console_input, items)
#5
I could not think of a simple solution with the dictionnary converted through AttrDict. However, here is a basic workaround that works with your input :
items = {"fruits":{"summerFruits":{"Mangoes":5,"melon":2}}}
wanted = "fruits.summerFruits.Mangoes"
#Converts the input to a list of strings (previously separated by dots)
words_list = []
element = ''
for char in wanted:
if char == '.': #chosen separator for input
words_list.append(element)
element = ''
else:
element = element + char
words_list.append(element)
#From the dict, get the value at the position indicated by the list of string keys
temp_dict = items
for key in words_list:
temp_dict = temp_dict.get(key)
value = temp_dict
Hoping this would work for your application, even though the syntax for getting the output is slightly different.

python get dictionary values list as list if key match

I have the following list and dictionary:
match_keys = ['61df50b6-3b50-4f22-a175-404089b2ec4f']
locations = {
'2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'],
'61df50b6-3b50-4f22-a175-404089b2ec4f': [
'7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce'
]
}
If I want to search 'locations' for keys that match in the match_keys list and extract their values, to get something like this...
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
...what would be the best way?
You can iterate over match_keys and use dict.get to get the values under each key:
out = [v for key in match_keys if key in locations for v in locations[key]]
Output:
['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
for key, value in locations.items():
if key == match_keys[0]:
print(value)
Iterate over keys and get value by [].
res = []
for key in matched_keys:
res.append(matched_keys[key])
or if you dont want list of lists you can use extend()
res = []
for key in matched_keys:
res.extend(matched_keys[key])

Convert String to multi-level dictionary keys?

I am giving the user the ability to check a specific key in a multi-level dictionary. My idea is that they will pass the path to the key like this:
root.subelement1.subelement2.key
This can be of arbitrary length and depth.
Once I have the string (above) from the user, I'll split it and get a list of each individual component:
elements = ['root', 'subelement1', 'subelement2', 'key']
All of this I can do. The next part is where I am stuck. How can I query the dictionary key, specified by the above when it's arbitrary length?
My initial thought was to do something like my_dict[elements[0]][elements[1]]...but that doesn't scale or work when my user doesn't pass exactly the length I expect.
How can I get the data at an arbitrary key depth, in this case?
A couple examples:
User passes country.US.NewYork => I query `my_dict['country']['US']['NewYork']
User passes department.accounting => I query my_dict['department']['accounting']
User passes id => I query my_dict['id']
User passes district.District15.HenryBristow.principal => I query my_dict['district']['District15']['HenryBristow']['principal']
you could do that using reduce which will query the keys in the nested dictionaries:
q = "district.District15.HenryBristow.principal"
my_dict = {"district" : {"District15" : {"HenryBristow" : {"principal" : 12}}}}
from functools import reduce # python 3 only
print(reduce(lambda x,y : x[y],q.split("."),my_dict))
result:
12
If you want to avoid to catch KeyError in case the data doesn't exist with this path, you could use get with a default value as empty dictionary:
reduce(lambda x,y : x.get(y,{}),q.split("."),my_dict)
Trying to get an unknown value returns an empty dictionary. The only drawback is that you don't know from where exactly the path got lost, so maybe leaving the KeyError be raised wouldn't be so bad:
try:
v = reduce(lambda x,y : x[y],q.split("."),my_dict)
except KeyError as e:
print("Missing key: {} in path {}".format(e,q))
v = None
Use recursion. Ex:
root = {
'subelement1': {
'subelement2': {
'key': 'value'
}
}
}
elements = ['subelement1', 'subelement2', 'key']
def getElem(d, keys):
if keys == []:
return None
else:
key = keys[0]
remainingKeys = keys[1:]
if remainingKeys == []:
return d[key]
else:
if type(d[key]) == dict:
return getElem(d[key], remainingKeys)
else:
return None
print(getElem(root, elements))
from a python 2.x perspective, you can do this with reduce.
query_list = keys.split(":")
print reduce(lambda x,y: x[y], [my_dict] + query_list)
But in general, you'll want to do this with a recursive or iterative function if you want to do error handling beyond throwing a KeyError.
You can transverse the dictionary using a for loop:
s = 'root.subelement1.subelement2.key'
d1 = {'root':{'subelement1':{'subelement2':{'key':15, 'key1':18}}}}
new_d = d1
for key in s.split('.'):
new_d = new_d[key]
print(new_d)
Output:
15
u can do this like below
my_dict = someDict
tmpDict = dict(someDict) # a coppy of dict
input = "x.u.z"
array = input.split(".")
for key in array:
tmpDict = tmpDict[key]
print(tmpDict)
but your question is very challenging:
u say if user send country.us then go to my-dict.country.us
but what happen if one of this path in my_dict be a list code will results error
u can handle this by check type
if isinstance(tmpDict , dict ):
tmpDict = tmpDict[key]
else:
# u should say what u want else (a Recursive method u will need)
edit
if user address maybe wrong you should check my_dict have this field or not sample code is below but will be many if i don't like that!
if key not in tmpDict:
print("Bad Path")
return

updating an input dictionary in python

I am defining a function
def update(dictionary,key,value):
dictionary[key] = value
# if i do print dictionary... it still shows the original value?
I want to update the input dictionary in the main call
So this is the main function i wrote:
def update_mapping(mapping_dict,check_word,solution_word):
#print "here "
#new_mapping_dict = {}
for i,ele in enumerate(check_word):
if mapping_dict.has_key(ele):
if mapping_dict[ele] == "*":
mapping_dict[ele] = solution_word[i]
print ele, solution_word
print mapping_dict,check_word,solution_word
Basically I am inputting a misspelled word and then misspelled word has some mapping..
I do that mapping in the dictionary..
Like
mapping_dict ={"a":"x"...."s":"*"...}
So all the known alphabets whose mapping have been found have a legit key value alphabet pairs..
for the alphabets for which I havent found the right mapping, I am replacing them with "*"
and I am finding them with some algorithm (inverted index)
And as i found those, I want to update my dictionary?
>>> test = {"test": 1}
>>> def update(dictionary,key,value):
... dictionary[key] = value
...
>>> update(test, "test", 2)
>>> test
{'test': 2}
Your problem must be elsewhere - this works.

How to print a dictionary's key?

I would like to print a specific Python dictionary key:
mydic = {}
mydic['key_name'] = 'value_name'
Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don't want all the keys listed, merely one specific key. For instance I'd expect something like this (in pseudo-code):
print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']
Is there any name_the_key() method to print a key name?
Edit:
OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because I realised 'key_name' and mydic['key_name'] are two different things and I thought it would be incorrect to print the 'key_name' out of the dictionary context. But indeed I can simply use the 'key_name' to refer to the key! :)
A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so
for key, value in mydic.iteritems() :
print key, value
Python 3 version:
for key, value in mydic.items() :
print (key, value)
So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.
Additionally you can use....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?
If so you want the following:
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
Make sure you use +'s instead of ,' as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.
dic = {"key 1":"value 1","key b":"value b"}
#print the keys:
for key in dic:
print key
#print the values:
for value in dic.itervalues():
print value
#print key and values
for key, value in dic.iteritems():
print key, value
Note:In Python 3, dic.iteritems() was renamed as dic.items()
The name of the key 'key_name' is 'key_name', therefore
print('key_name')
or whatever variable you have representing it.
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])
# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])
# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))
# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))
# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))
# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))
# To print all pairs of (key, value) one at a time
for e in range(len(x)):
print(([key for key in x.keys()][e], [value for value in x.values()][e]))
# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))
Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?
def key_for_value(d, value):
"""Return a key in `d` having a value of `value`."""
for k, v in d.iteritems():
if v == value:
return k
Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.
If you need to do this frequently, it would make sense to construct the reverse dictionary:
d_rev = dict(v,k for k,v in d.iteritems())
Update for Python3: d.iteritems() is not longer supported in Python 3+ and should be replaced by d.items()
d_rev = {v: k for k, v in d.items()}
# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}
# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')
# programmatic method:
for key, value in mapping.items():
print(f'{key}: {value}')
# yields:
# a 1
# b 2
# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))
# yields:
# a: 1
# b: 2
Edit: Updated for python 3's f-strings...
Make sure to do
dictionary.keys()
rather than
dictionary.keys
import pprint
pprint.pprint(mydic.keys())
Or you can do it that manner:
for key in my_dict:
print key, my_dict[key]
dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
# Choose key to print (could be a user input)
x = 'name'
if x in dict.keys():
print(x)
What's wrong with using 'key_name' instead, even if it is a variable?
Probably the quickest way to retrieve only the key name:
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
Result:
key_name
Converts the dictionary into a list then it lists the first element which is the whole dict then it lists the first value of that element which is: key_name
I'm adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented -- if updated for Python 3 per the suggested workaround in a comment to that answer -- silently fails to return all relevant data.
Background
I have some metabolic data, represented in a graph (nodes, edges, ...). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).
Find keys for given values
The following code correctly finds my keys, given values:
def k4v_edited(my_dict, value):
values_list = []
for k, v in my_dict.items():
if v == value:
values_list.append(k)
return values_list
print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]
whereas this code returns only the first (of possibly several matching) keys:
def k4v(my_dict, value):
for k, v in my_dict.items():
if v == value:
return k
print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)
The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.
I looked up this question, because I wanted to know how to retrieve the name of "the key" if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:
dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")
print(key_name) # equal to 'random_word', type: string.
Try this:
def name_the_key(dict, key):
return key, dict[key]
mydict = {'key1':1, 'key2':2, 'key3':3}
key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
If you want to get the key of a single value, the following would help:
def get_key(b): # the value is passed to the function
for k, v in mydic.items():
if v.lower() == b.lower():
return k
In pythonic way:
c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
"Enter a valid 'Value'")
print(c)

Categories