[英]Python dict in tuple
# A tuple from a dictionary of strings
t10 = tuple({1: 'one', 2: 'two', 3: 'three'})
print(t10) # (1, 2, 3)
# A tuple from a dictionary of list of strings
t11 = tuple({1: ['red', 'blue', 'green'], 2: ['black', 'white'], 3: ['golden', 'silver']})
print(t11) # (1, 2, 3)
如何訪問元組中定義的字典的值? 或者甚至有可能嗎?
你想使用.items()
d = {1: 'one', 2: 'two', 3: 'three'}
t = tuple(d.items()) # ((1, 'one'), (2, 'two'), (3, 'three'))
print(t[0][0]) # 1
print(t[0][1]) # 'one'
如果您嘗試創建一個包含 dict 的元組,則無需調用tuple
,您可以使用元組文字
>>> t10 = ({1: 'one', 2: 'two', 3: 'three'},) # note the trailing comma
>>> print(t10)
({1: 'one', 2: 'two', 3: 'three'},)
>>> print(t10[0][3])
three
>>>
>>> t11 = ({1: ['red', 'blue', 'green'], 2: ['black', 'white'], 3: ['golden', 'silver']},)
>>> print(t11)
({1: ['red', 'blue', 'green'], 2: ['black', 'white'], 3: ['golden', 'silver']},)
>>> print(t11[0][3])
['golden', 'silver']
您當前使用的方式是將 dict 用作可迭代對象並從其元素中構建一個元組。 對於字典,元素是鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.