Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tuples in Dicts

Is it possible in python to add a tuple as a value in a dictionary?
And if it is,how can we add a new value, then? And how can we remove and change it?

like image 552
FILIaS Avatar asked Nov 23 '09 18:11

FILIaS


2 Answers

>>> a = {'tuple': (23, 32)}
>>> a
{'tuple': (23, 32)}
>>> a['tuple'] = (42, 24)
>>> a
{'tuple': (42, 24)}
>>> del a['tuple']
>>> a
{}

if you meant to use tuples as keys you could do:

>>> b = {(23, 32): 'tuple as key'}
>>> b
{(23, 32): 'tuple as key'}
>>> b[23, 32] = 42
>>> b
{(23, 32): 42}

Generally speaking there is nothing specific about tuples being in dictionary, they keep behaving as tuples.

like image 68
SilentGhost Avatar answered Oct 09 '22 15:10

SilentGhost


Since tuples are immutable, you cannot add a value to the tuple. What you can do, is construct a new tuple from the current tuple and an extra value. The += operator does this for you, provided the left argument is a variable (or in this case a dictionary value):

>>> t = {'k': (1, 2)}
>>> t['k'] += (3,)
>>> t
{'k': (1, 2, 3)}

Regardless, if you plan on altering the tuple value, perhaps it's better to store lists? Those are mutable.

Edit: Since you updated your question, observe the following:

>>> d = {42: ('name', 'date')}
>>> d[42][0] = 'name2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

This happens because, as stated before, tuples are immutable. You cannot change them. If you want to change them, then in fact you'll have to create a new one. Thus:

>>> d[42] = ('name2', d[42][2])
>>> d
{42: ('name2', 'date')}

As a side note, you may want to use namedtuples. They work just like regular tuples, but allow you to refer to elements within the tuple by name:

>>> from collections import namedtuple
>>> Person = namedtuple('Person', 'name date')
>>> t = {42: Person('name', 'date')}
>>> t[42] = Person('name2', t[42].date)
>>> t
{42: Person(name='name2', date='date')}

  : Next time please edit your actual question. Do not post an answer containing only further questions. This is not a forum.

like image 22
Stephan202 Avatar answered Oct 09 '22 15:10

Stephan202