简体   繁体   English

从 python 中的字典中选择键

[英]Selecting the key from a dictionary in python

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.所以我需要有人来澄清为什么我必须把key: value_keys[key]以这种方式从字典中提取键。

Next, I need to know why I can't select specific keys from this code value_keys.keys() .接下来,我需要知道为什么我不能 select 这段代码中的特定键value_keys.keys()

Your code new = {key: value_keys[key] for key in ['text', 'lang']} is doing the same as this code:您的代码new = {key: value_keys[key] for key in ['text', 'lang']}与此代码的作用相同:

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中的每个键,并将相同的键和相同的值分配给名为new的新字典。

value_keys[key] returns the value of key in the dictionary value_keys . value_keys[key]返回字典value_keyskey的值。

Answer 1)答案 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.所以我需要有人来澄清为什么我必须把key: value_keys[key]以这种方式从字典中提取键。

You do not have to put key: value_keys[key] in that manner to extract the keys from the dictionary.您不必以这种方式放置key: value_keys[key]来从字典中提取键。 You can also use for loops:您还可以使用 for 循环:

for key in value_keys
   print(key)

or或者

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

Python How to iterate through dictionary Python 如何遍历字典

Answer 2)答案 2)

Next, I need to know why I can't select specific keys from this code value_keys.keys() .接下来,我需要知道为什么我不能 select 这段代码中的特定键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'): value_keys.keys()返回value_keys字典中所有键的列表,您可以通过遍历所有键的列表并检查键是否满足条件(在本例中我选择select 键,如果它被称为“文本”):

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 Python 检查字典中是否存在键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM