📌  相关文章
📜  Python – 提取字典中的第 K 个键

📅  最后修改于: 2022-05-13 01:55:09.494000             🧑  作者: Mango

Python – 提取字典中的第 K 个键

很多时候,在使用Python时,我们可能会遇到需要获取字典的第 K 个键的情况。它可以有许多特定用途,用于检查索引以及更多此类用途。这对于Python 3.8 + 版本很有用,其中键排序类似于插入排序。让我们讨论可以执行此任务的某些方式。

方法 #1:使用list() + keys()
上述方法的组合可用于执行此特定任务。在此,我们只需将 keys() 提取的整个字典的键转换为列表,然后访问第 K 个键。

# Python3 code to demonstrate working of
# Extracting Kth Key in Dictionary
# Using keys() + list()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 1
  
# Using keys() + list()
# Extracting Kth Key in Dictionary
res = list(test_dict.keys())[K]
  
# printing Kth key
print("The Kth key of dictionary is : " + str(res))
输出 :
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The Kth key of dictionary is : Gfg

方法 #2:使用next() + iter()
也可以使用这些功能来执行此任务。在此,我们只需使用 next() 获取第 K 个 next 键,并使用 iter函数获取字典项的可迭代转换。

# Python3 code to demonstrate working of
# Extracting Kth Key in Dictionary
# Using next() + iter()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 1
  
# Using next() + iter()
# Extracting Kth Key in Dictionary
test_dict = iter(test_dict)
for i in range(0, K + 1) :
    res = next(test_dict)
  
# printing Kth key
print("The Kth key of dictionary is : " + str(res))
输出 :
The original dictionary is : {'best': 3, 'Gfg': 1, 'is': 2}
The Kth key of dictionary is : Gfg