Get Dictionary Value by Key

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

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 single value from dictionary by key

It really does seem like you're overcomplicating this issue.

You can just use the indexer ([]) of the Dictionary class along with the .ContainsKey() method.

If you use something like this:

string value;
if (myDict.ContainsKey(key))
{
value = myDict[key];
}
else
{
Console.WriteLine("Key Not Present");
return;
}

You should achieve the effect that you want.

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

python 3 dictionary key to a string and value to another string

Use dict.items():

You can use dict.items() (dict.iteritems() for python 2), it returns pairs of keys and values, and you can simply pick its first.

>>> d = { 'a': 'b' }
>>> key, value = list(d.items())[0]
>>> key
'a'
>>> value
'b'

I converted d.items() to a list, and picked its 0 index, you can also convert it into an iterator, and pick its first using next:

>>> key, value = next(iter(d.items()))
>>> key
'a'
>>> value
'b'

Use dict.keys() and dict.values():

You can also use dict.keys() to retrieve all of the dictionary keys, and pick its first key. And use dict.values() to retrieve all of the dictionary values:

>>> key = list(d.keys())[0]
>>> key
'a'
>>> value = list(d.values())[0]
>>> value
'b'

Here, you can use next(iter(...)) too:

>>> key = next(iter(d.keys()))
>>> key
'a'
>>> value = next(iter(d.values()))
'b'

Ensure getting a str:

The above methods don't ensure retrieving a string, they'll return whatever is the actual type of the key, and value. You can explicitly convert them to str:

>>> d = {'some_key': 1}
>>> key, value = next((str(k), str(v)) for k, v in d.items())
>>> key
'some_key'
>>> value
'1'
>>> type(key)
<class 'str'>
>>> type(value)
<class 'str'>

Now, both key, and value are str. Although actual value in dict was an int.

Disclaimer: These methods will pick first key, value pair of dictionary if it has multiple key value pairs, and simply ignore others. And it will NOT work if the dictionary is empty. If you need a solution which simply fails if there are multiple values in the dictionary, @SylvainLeroux's answer is the one you should look for.

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

Get Dictionary key by using the dictionary value

A dictionary is really intended for one way lookup from Key->Value.

You can do the opposite use LINQ:

var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key);

foreach(var key in keysWithMatchingValues)
Console.WriteLine(key);

Realize that there may be multiple keys with the same value, so any proper search will return a collection of keys (which is why the foreach exists above).

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'

Dictionary get value without knowing the key

You just have to use dict.values().

This will return a list containing all the values of your dictionary, without having to specify any key.

You may also be interested in:

  • .keys(): return a list containing the keys
  • .items(): return a list of tuples (key, value)

Note that in Python 3, returned value is not actually proper list but view object.



Related Topics



Leave a reply



Submit