📜  Python – 在字典中附加字典键和值(按顺序)

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

Python – 在字典中附加字典键和值(按顺序)

给定一个字典,执行键的追加,然后是列表中的值。

方法 #1:使用 list() + keys() + values()

这是可以执行此任务的方式之一。在此,我们使用 keys() 和 values() 提取键和值,然后使用 list() 转换为列表并按顺序执行附加。

Python3
# Python3 code to demonstrate working of 
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using values() + keys() + list()
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# + operator is used to perform adding keys and values
res = list(test_dict.keys()) + list(test_dict.values())
  
# printing result 
print("The ordered keys and values : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using chain() + keys() + values()
from itertools import chain
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# chain() is used for concatenation
res = list(chain(test_dict.keys(), test_dict.values()))
  
# printing result 
print("The ordered keys and values : " + str(res))


输出
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]

方法#2:使用链()+键()+值()

这是可以执行此任务的方式之一。在此,我们使用 chain() 将键与值按顺序绑定在一起。

Python3

# Python3 code to demonstrate working of 
# Append Dictionary Keys and Values ( In order ) in dictionary
# Using chain() + keys() + values()
from itertools import chain
  
# initializing dictionary
test_dict = {"Gfg" : 1, "is" :  3, "Best" : 2}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# chain() is used for concatenation
res = list(chain(test_dict.keys(), test_dict.values()))
  
# printing result 
print("The ordered keys and values : " + str(res)) 
输出
The original dictionary is : {'Gfg': 1, 'is': 3, 'Best': 2}
The ordered keys and values : ['Gfg', 'is', 'Best', 1, 3, 2]