Home > other >  Python dict in tuple
Python dict in tuple

Time:08-05

# 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)

How can I access the values of the dict defined in the tuple? OR is it even possible?

CodePudding user response:

You want to use .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'

CodePudding user response:

If you are trying to create a tuple containing a dict, you don't need to call tuple, you can use a tuple literal

>>> 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']

The way you are currently using is using the dict as an iterable and building a tuple out of its elements. For a dict, the elements are the keys.

  • Related