Skip to content Skip to sidebar Skip to footer

Create A Dict If Its Not Already Created And Then Append To It

I have a list of files in which I need to select few lines which has CommonChar in them and work on creating a dictionary. The lines in a file which I am interested in look like t

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:

  1. create a dictionary containing information about apples
  2. assign that dictionary to the variable apple
  3. check if this just created dictionary is already in mainDict
  4. 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"