Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dictionaries to tuple

Tags:

python

tuples

I'm new to python. I have tuple. It's have a elements /dictionaries/. I need a add new dictionaries to tuple? How to do it? I'm using python 2.7. Thank you for every help.

like image 218
Zeck Avatar asked Aug 05 '11 02:08

Zeck


3 Answers

As Chris Gregg said, you can't add anything to a tuple that already exists. You can add two tuples to create a new one though.

>>> t = (1, 2, 3)
>>> d = {'a':1, 'b':2, 'c':3}
>>> t + (d,)
(1, 2, 3, {'a': 1, 'c': 3, 'b': 2})

The old tuple remains the same:

>>> t
(1, 2, 3)

You could also do this:

t += (d,)

which is shorthand for

t = t + (d,)
like image 174
senderle Avatar answered Oct 13 '22 23:10

senderle


You can't add anything to a tuple, as it is immutable. In order to add a dictionary to a new tuple, you simply put them into parenthesis, separated by commas:

myTuple = (dict1, dict2, dict3)
like image 25
Chris Gregg Avatar answered Oct 14 '22 00:10

Chris Gregg


Why use a tuple ? they are made so you cannot add new values after you define it you can only "summon" a new one . And if you already have a tuple you can transform your tuple in to a list to for the exchange period .

d = {'a':'val1' , 'b': 'val2'}
tuple1 = ( 1 , 2 , 3 )
list1 = list(tuple1).append(d)

this way you can use the list if you ever want to add something new to it and summon some other tuple. and if you really want it to be a tuple back use the tuple function .

tuple2 = tuple(list1)

Any way i hope you got the point of lists and tuples .

like image 1
Florin Avatar answered Oct 14 '22 01:10

Florin