📌  相关文章
📜  Python|将字典键和值拆分为单独的列表

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

Python|将字典键和值拆分为单独的列表

给定一个字典,任务是将该字典拆分为键和值到不同的列表中。让我们讨论一下我们可以做到这一点的不同方法。

方法#1:使用built-in functions

# Python code to demonstrate
# to split dictionary
# into keys and values
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print("intial_dictionary", str(ini_dict))
  
# split dictionary into keys and values
keys = ini_dict.keys()
values = ini_dict.values()
  
# printing keys and values separately
print ("keys : ", str(keys))
print ("values : ", str(values))
输出:
intial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}
keys :  dict_keys(['a', 'b', 'c'])
values :  dict_values(['akshat', 'bhuvan', 'chandan'])


方法 #2:使用zip()

# Python code to demonstrate
# to split dictionary
# into keys and values
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print("intial_dictionary", str(ini_dict))
  
# split dictionary into keys and values
keys, values = zip(*ini_dict.items())
  
# printing keys and values separately
print ("keys : ", str(keys))
print ("values : ", str(values))
输出:
intial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}
keys :  ('a', 'c', 'b')
values :  ('akshat', 'chandan', 'bhuvan')


方法 #3:使用items()

# Python code to demonstrate
# to split dictionary
# into keys and values
  
# initialising _dictionary
ini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'}
  
# printing iniial_dictionary
print("intial_dictionary", str(ini_dict))
  
# split dictionary into keys and values
keys = []
values = []
items = ini_dict.items()
for item in items:
    keys.append(item[0]), values.append(item[1])
  
# printing keys and values separately
print ("keys : ", str(keys))
print ("values : ", str(values))
输出:
intial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}
keys :  ['b', 'c', 'a']
values :  ['bhuvan', 'chandan', 'akshat']