📜  Python – 将元组连接到字典键

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

Python – 将元组连接到字典键

给定元组,将它们转换为字典,键为连接字符串。

方法 #1:使用循环 + join()

在此,我们使用 join() 执行字典键的连接任务,并使用循环来呈现所需的字典。

Python3
# Python3 code to demonstrate working of 
# Concatenate Tuple to Dictionary Key
# Using loop + join()
  
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = {}
for sub in test_list:
      
  # joining for making key
  res[" ".join(sub[0])] = sub[1]
  
# printing result 
print("The computed Dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Concatenate Tuple to Dictionary Key
# Using dictionary comprehension
  
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one liner to solve problem 
res = {' '.join(key): val for key, val in test_list}
  
# printing result 
print("The computed Dictionary : " + str(res))


输出
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}

方法#2:使用字典理解

这是上述方法的简写,类似的功能,只是在纸上的一行,用于紧凑的解决方案。

Python3

# Python3 code to demonstrate working of 
# Concatenate Tuple to Dictionary Key
# Using dictionary comprehension
  
# initializing list
test_list = [(("gfg", "is", "best"), 10), (("gfg", "good"), 1), (("gfg", "for", "cs"), 15)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# one liner to solve problem 
res = {' '.join(key): val for key, val in test_list}
  
# printing result 
print("The computed Dictionary : " + str(res))
输出
The original list is : [(('gfg', 'is', 'best'), 10), (('gfg', 'good'), 1), (('gfg', 'for', 'cs'), 15)]
The computed Dictionary : {'gfg is best': 10, 'gfg good': 1, 'gfg for cs': 15}