Get Dictionary Key by Value

Get key by value in dictionary

There is none. dict is not intended to be used this way.

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items(): # for name, age in dictionary.iteritems(): (for Python 2.x)
if age == search_age:
print(name)

Get dictionary value by key

It's as simple as this:

String xmlfile = Data_Array["XML_File"];

Note that if the dictionary doesn't have a key that equals "XML_File", that code will throw an exception. If you want to check first, you can use TryGetValue like this:

string xmlfile;
if (!Data_Array.TryGetValue("XML_File", out xmlfile)) {
// the key isn't in the dictionary.
return; // or whatever you want to do
}
// xmlfile is now equal to the value

Getting key with maximum value in dictionary?

You can use operator.itemgetter for that:

import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]

And instead of building a new list in memory use stats.iteritems(). The key parameter to the max() function is a function that computes a key that is used to determine how to rank items.

Please note that if you were to have another key-value pair 'd': 3000 that this method will only return one of the two even though they both have the maximum value.

>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'

If using Python3:

>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'

How to get the key from value in a dictionary in Python?

You can write a list comprehension to pull out the matching keys.

print([k for k,v in a.items() if v == b])

How can I get dictionary key as variable directly in Python (not by searching from value)?

You should iterate over keys with:

for key in mydictionary:
print "key: %s , value: %s" % (key, mydictionary[key])

How to print Specific key value from a dictionary?

It's too late but none of the answer mentioned about dict.get() method

>>> print(fruit.get('kiwi'))
2.0

In dict.get() method you can also pass default value if key not exist in the dictionary it will return default value. If default value is not specified then it will return None.

>>> print(fruit.get('cherry', 99))
99

fruit dictionary doesn't have key named cherry so dict.get() method returns default value 99

Get dictionary key by value

Values do not necessarily have to be unique, so you have to do a lookup. You can do something like this:

var myKey = types.FirstOrDefault(x => x.Value == "one").Key;

If values are unique and are inserted less frequently than read, then create an inverse dictionary where values are keys and keys are values.

How to get dictionary key by providing a value as a condition

You should use dict.items() to iterate over all key, value pairs in a dictionary:

dict = {'cats' : '5', 'dogs' : '4', 'fish' : '7', 'rabbits': '4'}
my_list = ['2','3','4']

for k,v in dict.items():
if v == my_list[2]:
print(k)

Outputs:

dogs
rabbits

How do I sort a dictionary by value?

Python 3.7+ or CPython 3.6

Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.

>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

or

>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Older Python

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

In Python3 since unpacking is not allowed we can use

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])

If you want the output as a dict, you can use collections.OrderedDict:

import collections

sorted_dict = collections.OrderedDict(sorted_x)

How do I print the key-value pairs of a dictionary in python

Python 2 and Python 3

i is the key, so you would just need to use it:

for i in d:
print i, d[i]

Python 3

d.items() returns the iterator; to get a list, you need to pass the iterator to list() yourself.

for k, v in d.items():
print(k, v)

Python 2

You can get an iterator that contains both keys and values. d.items() returns a list of (key, value) tuples, while d.iteritems() returns an iterator that provides the same:

for k, v in d.iteritems():
print k, v


Related Topics



Leave a reply



Submit