Reputation: 325
I have this predefined dicitonary :
customMappingDict = {'Validated' : '',
'notValidated' : ''}
I want to add new dictionaries(!?) if possible to the existing key as its value, as in :
customMappingDict = {'Validated' : 'Key: 'Value', Key1: 'Value'',
'notValidated' : 'Key: 'Value', Key1: 'Value''}
For the resulting dictionary I would like to call upon the two preexisting keys(Validated and notValidated) and cycle the keys from its value(!?) as so :
for key in customMappingDict['Validated'].keys():
pass
...
Output should be :
key, key1
What I've tried :
if condition:
str1 = '{}'.format(provLst[0])
customMappingDict['Validated']: dict[str1]= '{}'.format(provLst[1])
else:
str2 = '{}'.format(provLst[0])
customMappingDict['notValidated']: dict[str2] = '{}'.format(provLst[1])
The worning that i'm getting in PyCharm :
Class 'type' does not define '__getitem__', so the '[]' operator cannot be used on its instances
Upvotes: 2
Views: 93
Reputation: 628
Try this
Suppose i have a dict
d = {'red': 100, 'green': 1000}
Now I want to change the value of 'red' to a dict
d['red'] = dict()
d['red']['light_red'] = 100.10
d['red']['dark_red'] = 100.20
Now will be
{'red': {'light_red': 100.10, 'dark_red': 100.20}, 'green': 1000}
Upvotes: 0
Reputation: 12992
Using collections.defaultdict
will save you a lot of the headache. The idea of defaultdict
is to create a dictionary that has a default value. In this case, the default value will be a dictionary as well.
You can do that simply like so:
from collections import defaultdict
customMappingDict = defaultdict(dict)
if condition:
str1 = '{}'.format(provLst[0])
customMappingDict['Validated'][str1] = f'{provLst[1]}'
else:
str2 = '{}'.format(provLst[0])
customMappingDict['notValidated'][str2] = f'{provLst[1]}'
SideNote: f{provLst[0]}
is the same as '{}'.format(provLst[0])
just cleaner !!
Upvotes: 2