Create A Dict If Its Not Already Created And Then Append To It
Solution 1:
Check out defaultdict! Import with from collections import defaultdict
. If you start with mainDict = defaultdict(dict)
it will automatically create the dictionary if you try to assign a key. mainDict['Apple']['American'] = '16'
will work like magic.
If you need to increment new keys in the sub dictionaries, you can also put a defaultdict in a defaultdict
documentation: https://docs.python.org/3/library/collections.html#collections.defaultdict
Solution 2:
'Apple' and 'Grapes' can't be created as dictionaries since they are strings. I'm assuming you have a flow in your program that goes something like this:
- create a dictionary containing information about apples
- assign that dictionary to the variable apple
- check if this just created dictionary is already in mainDict
if not, add it to the values of mainDict under the key 'Apple'
mainDict= {'Grapes':{'Arabian':'25','Indian':'20'} } apple = {'American':'16', 'Mexican':10, 'Chinese':5} if apple not in mainDict.values(): mainDict['Apple'] = apple mainDict
output:
{'Apple': {'American': '16', 'Chinese': 5, 'Mexican': 10},
'Grapes': {'Arabian': '25', 'Indian': '20'}}
The problem I think you have, is that there's no general way to get the name of an object as a string. Dicts don't have a name attribute. Refer to these answers: How can I get the name of an object in Python?
Post a Comment for "Create A Dict If Its Not Already Created And Then Append To It"