Python code reading (Chapter 59): query the dictionary key value according to value

Time:2022-5-9
Python code reading (Chapter 59): query the dictionary key value according to value

Introduction to Python code reading collection:Why not recommend Python beginners to directly look at the project source code

The code read in this article implementsvalueQuery dictionarykeyThe function of.

The code snippet read in this article comes from30-seconds-of-python

find_keys

def find_keys(dict, val):
  return list(key for key, value in dict.items() if value == val)

# EXAMPLES
ages = {
  "Peter": 10,
  "Isabel": 11,
  "Anna": 10,
}
print(find_keys(ages, 10)) # [ "Peter", "Anna" ]

find_keysFunction receives a dictionary and avalValue to return a list of key values.

Function in a generator expression, useitems()Gets the name of the dictionaryk-vValue pair, whenvalueGets when the value and input are equalkeyValue of. Finally reuselist()Convert the generator into a list.

find_key

def find_key(dict, val):
  return next(key for key, value in dict.items() if value == val)

# EXAMPLES
ages = {
  "Peter": 10,
  "Isabel": 11,
  "Anna": 9,
}
print(find_key(ages, 11)) # "Isabel"

find_keyFunction receives a dictionary and avalValue, return the firstvalueSame valuekeyValue.

andfind_keysSimilarly, use a generator expression to get the specifiedvalueKey value of. The difference is that the generator is used outsidenext()Function to get the next value of the generator. In this functionnext()Only called once, so the first qualified is obtainedkeyValue.

next(iterator[, default])Function by callingiteratorof__next__()Method to get the next element. If the iterator is exhausted, the given value is returneddefault, triggered if there is no default valueStopIteration

Recommended Today

Image training method

Some people can keep calm in the face of unprepared emergencies. This is not a talent. No one is born with the ability to adapt. It’s all trained. There is a method that has been used in all walks of life, and people with all kinds of personalities can get promotion from it, which is […]