Selecting the key from a dictionary in python

Viewed 66
new = {key: value_keys[key] for key in ['text', 'lang']} 

So I need someone to clarify why I have to put key: value_keys[key] In this manner to extract the keys from the dictionary.

Next, I need to know why I can't select specific keys from this code value_keys.keys().

1 Answers

Your code new = {key: value_keys[key] for key in ['text', 'lang']} is doing the same as this code:

for key in ['text', 'lang']:
   new[key] = value_keys[key]

You are essentially iterating over each key in value_keys and assigning the same key and the same value to a new dictionary called new.

value_keys[key] returns the value of key in the dictionary value_keys.

Answer 1)

So I need someone to clarify why I have to put key: value_keys[key] In this manner to extract the keys from the dictionary.

You do not have to put key: value_keys[key] in that manner to extract the keys from the dictionary. You can also use for loops:

for key in value_keys
   print(key)

or

for key in value_keys.keys()
   print(key)

Python How to iterate through dictionary

Answer 2)

Next, I need to know why I can't select specific keys from this code value_keys.keys().

value_keys.keys() is returning a list of all the keys in the value_keys dictionary, you can select a specific key from the list by iterating through the list of all keys and checking if the key meets a condition (in this example I chose to select the key if it was called 'text'):

for key in value_keys.keys():
   if(key == "text"):
      print(key)

If you just want to check whether or not a key is in a dictionary you can use:

if key in value_keys:
   #code to execute if the key is in the dictionary
else:
   #code to execute if the key is not in the dictionary

Python check if key exists in dictionary

Related