Suppose I have a dictionary as below
my_dict = {
'key1' : 'str1',
'key2' : 'str2',
'key3' : 'str3'
}
I want to assign additional value to each key so that the structure of dictionary is as follows
key1 : str1, num1
key2 : str2, num2
key3 : str3, num2
Is it possible to do it, if yes then how can we access individual values.
If you don't need to change these multiple values in the dictionary, use tuples
as values:
my_dict = {
'key1' : ('str1', 56),
'key2' : ('str2', 78),
'key3' : ('str3', 89)
}
Otherwise use lists
:
my_dict = {
'key1' : ['str1', 56],
'key2' : ['str2', 78],
'key3' : ['str3', 89]
}
And in both structures, accessing is identical:
>>> my_dict['key3']
('str3', 89)
>>> my_dict['key3'][0]
'str3'
But assignment is only possible with lists
(as they are mutable
data structures):
>>> my_dict['key3'][1] = 99
>>> my_dict['key3'][1]
99
>>> my_dict
{'key3': ['str3', 99], 'key1': ['str1', 56], 'key2': ['str2', 78]}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments