Can we assign 2 types of values to a key in a dictionary

Olivia Brown

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.

Joe Iddon

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.

edited at
0

Comments

0 comments
Login to comment

Related

Trying to assign 2 values or more to a dictionary key using variables?

Can we assign values to function?

How to assign multiple values to key in dictionary

How can we merge key value of dictionary?

how can I create nested dictionary keys and assign them values from a list of namespaced key value pairs?

How can we assign dictionary titles to items in a list?

How to assign multiple values to a key in a dictionary, multiple times using pandas

How to assign two new key values in a JObject from a dictionary?

Using input to find a key in a dictionary and assign the values to that variable

can we assign session values to cgridview without dataprovider

How can I assign a tuple to a dictionary key in Python?

Insert NSMutableArray data into Dictionary with one key and multiple types of values

Create a dictionary from key value, where the keys and values are pair types

Why can I assign an empty object types {[key: string]: number}

How can I assign two types to a specific key in mongoose schema?

What happens when we assign 2 values to same variable?

How to select some key values from a dictionary and assign to another dictionary in python

How can we pass 2 values in PHP?

Mismatching types 'Int64' and '_' when trying to assign optional Int64 to a dictionary key

Assign array to key dictionary in python

How can I assign a key to an array of values to pass to an API?

Swift 2: How can i assign a dictionary to AnyObject?

Dictionary Functions: Can you assign an argument to a "Tier 2" function?

Can we hold 2 data types in a STL list?

Assign list values to dictionary keys

assign list values to dictionary python

Float values as dictionary key

Dictionary Key Values

Aggregate values in dictionary by key