There exists a dictionary.
my_dict = {'alpha':{'a':1, 'b':2, 'c':3}}
How to return a single list with one key inside which refers to the greatest value. If there are multiple occurrences of the greatest value then return a list with keys of similar value.
You can use max to get the maximum value, and extract the keys that has that value:
max_value = max(my_dict['alpha'].values())
print([key for key, value in my_dict['alpha'].items() if value == max_value])
Related
I am looking to solve a problem to compare the string of the key and value of the same dictionary.
To return a dictionary of all key and values where the value contains the key name as a substring.
a = {"ant":"antler", "bi":"bicycle", "cat":"animal"}
the code needs to return the result:
b = {"ant":"antler", "bi":"bi cycle"}
You can iterate through the dictionary and unpack the key and the value at the same time this way:
b = {}
for key, value in a.items():
if value in key:
b[value] = key
This will generate your wanted solution. It does that by unpacking both the key and the value and checking if they match afterward.
You can also shorten that code by using a dictionary comprehension:
b = {key:value for key, value in a.items() if key in value}
This short line does the exact same thing as the code before. It even uses the same functionalities with only one addition - a dictionary comprehension. That allows you to put all that code in one simple line and declare the dictionary on the go.
answer = {k:v for k,v in a.items() if k in v}
Notes:
to iterate over key: value pair we use dict.items();
to check if a string is inside some other string we use in operator;
to filter items we use if-clause in the dictionary comprehension.
See also:
about dictionary comprehensions
about operators in and not in
I have a dictionary like this:
dictionary={('I', 'We', 'They'): 'X'}
For example I want to check is there 'I' in this dictionary and if it is true, return 'X'. Is there any solution?
I suppose you want more elements in your dictionary, so you will have to iterate over the keys of your dictionary and return when you found the right key. Like this:
def find_element(element):
keys = dictionary.keys()
for key in keys:
if element in key:
return dictionary[key]
You can call this function with "I" as element and you'll find the right value to your key.
My goal is to do the following:
Evaluate the existing dictionary using [key(string), item(int), format] and find the item in the dictionary with highest value in key-value pair.
Output the corresponding item (i.e. key value) with the highest value
For example consider the following code:
emails={}
emails={'abc#abc.org':1, 'bcd#bcd.org':2, 'efg#efg.org':3'}
The output should be, in the above example, ('efg#efg.org', 3)
Thank you for your time.
If you want the max evaluated by value then you can do
>>> max(emails.items(), key=lambda x:x[1])
('efg#efg.org', 3)
This solution finds the key with the maximum value; you can then access the dictionary with that key if you want the (key, value) pair.
>>> k = max(emails, key=emails.get)
>>> (k, emails[k])
('efg#efg.org', 3)
I have the following data structure whereby I would like to extract a given key: value pair by searching for the specific value. Use Case: I need to extract u'LOB_B': u'mcsmsg.example.net' from the dict.
{u'status': u'successful',
u'availableFqdnList': [
{u'LOB_A': u'pcload.us.example.net'},
{u'LOB_B': u'mcsmsg.example.net'},
{u'LOB_B': u'gtxd.example.net'},
{u'LOB_B': u'diamond.example.net'}]}
for key, value in my_dict.values():
if value == 'mcsmsg.example.net':
print("Print key value pairs for available FQDN list")
print key, "=", value
Error = for key, value in my_dict.values():
ValueError: too many values to unpack
I don't think values() is the function you want.
Probably you want items() instead.
If you are using python2, you can using iteritems()
Or for python3, it's items()
They will iter the key, value in the dictionary for you.
dic = {'a':1,'b':2}
for key,value in dic.items():
print(key)
print(value)
it will return
a
1
b
2
As a simple to understand way of getting this done
d = {u'status': u'successful',
u'availableFqdnList': [{u'LOB_A': u'pcload.us.example.net'},
{u'LOB_B': u'mcsmsg.example.net'},
{u'LOB_B': u'gtxd.example.net'},
{u'LOB_B': u'diamond.example.net'}]}
for val in d['availableFqdnList']:
if val.values()[0] == "mcsmsg.example.net":
print("%s=%s" %(val.keys()[0], val.values()[0]))
I have a dictionary like this:
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
I need to remove duplicate values from the lists. I wrote a function to do this:
no_dups = {}
for keys in dct:
if isinstance(dct[keys], list) and keys != 'dontCareAboutThisKey':
for value in dct[keys]:
if value not in no_dups.values():
no_dups[keys].append(value)
else:
no_dups[keys] = dct[keys]
I'm checking if value of the current key is a list. If no, it just 'copy' key to no_dups dictionary. If it is a list and not a key that I don't care about (there are no duplicates for sure) - it should check if current value already exists in no_dups.values() and append it to current key. Problem is that I'm getting an error:
KeyError: 'two:'
I know it's because I'm trying to add a value to non existing key but I have no idea how to deal with this and make it work.
I think the best way to deal with adding the key and appending at the same time is with dicts' setdefault() method:
no_dups.setdefault(keys,[]).append(value)
But rather than that, you can do this in a more neat way like this:
#remove duplicates
no_dups = {k:list(set(v)) if isinstance(v, list) and k != 'dontCareAboutThisKey' else v
for k,v in dct.items()} # or dct.iteritems() if using python2.x
That hack will, for key value combinations that pass the if test, convert the list into a set (removing duplicates) and then in a list again. For other key value combinations it will leave it intact.
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
set(dct) returns a set, which is a list without duplicates:
for key, value in dct.items():
if not isinstance(value, basestring):
dct[key] = set(value)
If you need a new dictionary you could do:
new_dct = {}
for key, value in dct.items():
if not isinstance(value, basestring):
new_dct[key] = set(value)
else:
new_dct[key] = value
If You want to remove duplicates, just change You list to set, with set() function:
https://docs.python.org/2/tutorial/datastructures.html#sets
It automatically gives You unique set, then You can always change it back to list.