开发者

Tuples in Dicts

开发者 https://www.devze.com 2022-12-12 12:41 出处:网络
Is it possible in python to add a tuple as a value in a dictionary? And 开发者_JAVA技巧if it is,how can we add a new value, then? And how can we remove and change it?>>> a = {\'tuple\': (23,

Is it possible in python to add a tuple as a value in a dictionary?

And 开发者_JAVA技巧if it is,how can we add a new value, then? And how can we remove and change it?


>>> 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.


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.


You can't change a tuple itself. You have to replace it by a different tuple.

When you use a list, you could also add values to it (changing the list itself) without need to replace it:

>> a = {'list': (23, 32)}
>> a
{'list': [23, 32]}
>> a['list'].append(99)
>> a
{'list': [23, 32, 99]}

In most cases, lists can be used as replacement for tuples (since as much I know they support all tuple functions -- this is duck typing, man!)


t1=('name','date')
t2=('x','y')

# "Number" is a String key!
d1={"Number":t1}
# Update the value of "Number"
d1["Number"] = t2

# Use a tuple as key, and another tuple as value
d1[t1] = t2

# Obtain values (getters)

# Can throw a KeyError if "Number" not a key
foo = d1["Number"]

# Does not throw a key error, t1 is the value if "Number" is not in the dict
d1.get("Number", t1)

# t3 now is the same as t1
t3 = d1[ ('name', 'date') ]

You updated your question again. Please take a look at Python dict docs. Python documentation is one of it's strong points! And play with the interpreter (python)on the command line! But let's continue.

  1. initially key 0

    d[0] = ('name', datetime.now())

  2. id known d1 = d[0] del d[0]

  3. name changed tmp = d1 d1 = ( newname, tmp1 )

And please consider using a

class Person(object):
    personIdCounter = 1
    def __init__(self):
      self.id = Person.personIdCounter
      Person.personIdCounter += 1
      self.name
      self.date

then

persons = {}
person = Person()
persons[person.id] = person
person.name = "something"

persons[1].name = "something else"

That looks better than a tuple and models your data better.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号