3

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.

Olivia Brown
  • 594
  • 4
  • 15
  • 28
  • 4
    Assign a list or tuple as the value. `d = {'k1': ['str1', 1]}`. Access via indexing, e.g. `d['k1'][0]` yields `str1` – Alexander Jan 18 '18 at 19:52
  • Use a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple) – wwii Jan 18 '18 at 19:54
  • It's not clear to me how exactly the output should look like. Could you clarify it with an example of how *you want the output to work* (should the values be concatenated strings or do you want to index the dictionary values or even index the dictionary keys?) – MSeifert Jan 18 '18 at 20:07

5 Answers5

3

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]}
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
1

Yes, you could assign a tuple:

my_dict = {
  'key_0': ('val_0', 'val_1')
  ...
}

And access like so:

my_dict['key_0'][0]   # 'val_0'
Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
1

you can add the value as a tuple or a list like this:

my_dict = {
'key1' : [str1, num1],
'key2' : [str2, num2],
'key3' : [str2, num2]
}

This would be the list way to do it. You could access your values with the corresponding indexes.

my_dict['key1'][0] would be the string and my_dict['key1'][1] would be the number.

Good luck!

Andre
  • 4,185
  • 5
  • 22
  • 32
1

you can establish lists if you want to later append

d= {'a':[1], 'b':[10]}
d['a'].append(2)
print(d) # {'a': [1, 2], 'b': [10]}
print(d['a'][1]) # 2
yoyoyoyo123
  • 2,362
  • 2
  • 22
  • 36
0

Given a list of your new numbers, you can use zip:

nums = [3, 4, 5]
my_dict = {
 'key1' : 'str1',
 'key2' : 'str2',
 'key3' : 'str3'
}
my_dict = {a:[b, c] for c, [a, b] in zip(nums, my_dict.items())}

Output:

{'key1': ['str1', 5], 'key2': ['str2', 4], 'key3': ['str3', 3]}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102