📜  Python - 创建元组字典

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

Python - 创建元组字典

在本文中,我们将讨论如何在Python中创建元组字典。

以元组为键的元组字典

在这里,我们将键作为字典中的元组传递

句法:

{(tuple1):value,(tuple2):value,.........,(tuple3):value}

这里的元组是作为某个值的键的元素的集合

示例: Python程序,用于创建以元组为键的元组字典

Python3
# tuple of favourite food as key
# value is name of student
data = {("chapathi", "roti"): 'Bobby', 
        ("Paraota", "Idly", "Dosa"): 'ojaswi'}
  
# display
data


Python3
# tuple of favourite food as value
# key is name of student
data = {'Bobby': ("chapathi", "roti"), 
        'ojaswi': ("Paraota", "Idly", "Dosa")}
  
# display
data


Python3
# one value is age of student
# second value is student name
data = ((24, "bobby"), (21, "ojsawi"))
  
# convert into dictionary
final = dict((value, key) for key, value in data)
  
# display
print(final)


输出:

{('Paraota', 'Idly', 'Dosa'): 'ojaswi', ('chapathi', 'roti'): 'Bobby'}

以元组为值的元组字典

在这里,我们将值作为字典中的元组传递

句法:

{key:(tuple),key :(tuple2).........,key:(tuple)}

这里的元组是代表某个键的某个值的元素集合。

示例:用元组作为值创建元组字典的Python程序

蟒蛇3

# tuple of favourite food as value
# key is name of student
data = {'Bobby': ("chapathi", "roti"), 
        'ojaswi': ("Paraota", "Idly", "Dosa")}
  
# display
data

输出:

{'Bobby': ('chapathi', 'roti'), 'ojaswi': ('Paraota', 'Idly', 'Dosa')}

从元组创建字典

在这里,我们将从嵌套的元组创建一个字典,为此我们需要在每个元组中传递两个值,一个代表键,另一个代表字典中的对应值。

句法:

dict((value, key) for key,value in nested_tuple)

示例:从元组创建字典

蟒蛇3

# one value is age of student
# second value is student name
data = ((24, "bobby"), (21, "ojsawi"))
  
# convert into dictionary
final = dict((value, key) for key, value in data)
  
# display
print(final)

输出:

{'bobby': 24, 'ojsawi': 21}