0

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 these:

CommonChar uniqueName field value 

CommonChar uniqueName field1 value1

CommonChar uniqueName1 field value

CommonChar uniqueName1 field1 value1 

So with this I would want a final dictionary which will store internal dictionaries named on uniqueName and key value pairs as (field: value, field1:value1)

This way I will have a main dict with internal dict based on uniqueName and key value pairs.

Final output should look like this:

mainDic={'uniqueName': {'field':'value', 'field1':value1, 'field2':value2},
          'uniqueName1':{'field':'value', 'field1':value1, 'field2':value2} }
jpp
  • 159,742
  • 34
  • 281
  • 339
Heyya
  • 57
  • 6

2 Answers2

0

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

whp
  • 1,406
  • 10
  • 10
  • If you want to use `dict` and manually check, it looks like there are plenty of threads on that (e.g. the possible duplicates). – whp Mar 22 '18 at 18:56
0

'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?

jhere
  • 1
  • 3