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.
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,)
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)
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With