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)
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 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
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 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 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
Use python function to get key by value in dictionary and return either key or None'
You can revise your function to be
def find_key(input_dict, value):
for key, val in input_dict.items():
if val == value: return key
return "None"
which means the function only returns the string "None"
if the loop has already ended. In your original version, the loop will exit after the first iteration because it hits a return
keyword. Also, if you are returning special Python None
instead of a string "None"
, you don't even need to return anything explicitly because None
is the default return value of a function without a return
keyword.
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.
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
Related Topics
Tkinter.Photoimage Doesn't Not Support Png Image
Cross-Platform Space Remaining on Volume Using Python
Why Is the Command Bound to a Button or Event Executed When Declared
Tkinter: Attributeerror: Nonetype Object Has No Attribute ≪Attribute Name≫
How to Listen For 'Usb Device Inserted' Events in Linux, in Python
How Would I Build Python Myself from Source Code on Ubuntu
How to Get Output from Subprocess.Popen(). Proc.Stdout.Readline() Blocks, No Data Prints Out
Python - Is Time.Sleep(N) Cpu Intensive
How to Make a Python, Command-Line Program Autocomplete Arbitrary Things Not Interpreter
How to Update-Alternatives to Python 3 Without Breaking Apt
Understanding Python Subprocess.Check_Output'S First Argument and Shell=True
How to Store the Result of an Executed Shell Command in a Variable in Python
How to Remove Items from a List While Iterating
How to Split a List into Equally-Sized Chunks
Deploying a Minimal Flask App in Docker - Server Connection Issues
Logical Operators For Boolean Indexing in Pandas
How to Download a File Over Http
Indentationerror: Unindent Does Not Match Any Outer Indentation Level