Home > Net >  How to add values to a dictionary with the values as dictionaries
How to add values to a dictionary with the values as dictionaries

Time:11-20

I feel like this should be really easy but I can't find it on the internet and I can't figure it out myself. I have a dictionary with its values being another dictionary. Now I want to add new data to these dic values. How do I do this since I can't use append add or =.

{'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000'}}

I need to be able to add this every time even when I don't know what the last value key is 3: .. or 4:.. etc etc. So after adding data it looks like:

{'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000', 3:'54353', 4: '235234234'}}

Thanks!

CodePudding user response:

You can get the max key of the subdict and increase to get a new one:

d = {'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000'}}

def add_subdict(d, value, key='high'):
    d[key][max(d[key].keys()) 1] = value

add_subdict(d, '123')   
add_subdict(d, '456')

output:

>>> d
{'high': {0: '57798.68000000',
  1: '57784.43000000',
  2: '57909.99000000',
  3: '123',
  4: '456'}}

version to handle missing keys:

def add_subdict(d, value, key='high'):
    if key not in d:
        d[key] = {0: value}
        return
    d[key][max(d[key].keys()) 1] = value
d = {'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000'}}
add_subdict(d, '456', key='other')

# {'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000'},
#  'other': {0: '456'}}

CodePudding user response:

Try converting it to string then converting back to dict

  import ast   
    thisdict = {
      "brand": "Ford",
      "electric": False,
      "year": 1964,
      "colors": ["red", "white", "blue"]
    }
    
    stra = str(thisdict)
    stra = stra.replace("}","")
    stra  = ',"a":0}'
    x = ast.literal_eval(stra)
    print(x)

CodePudding user response:

If your keys of the 'inner' dictionary is really just an enumeration:

my_dods = {'high': {0: '57798.68000000', 1: '57784.43000000', 2: '57909.99000000'}}
my_dods['high'][len(my_dods['high'])] = '54353'
my_dods['high'][len(my_dods['high'])] = '235234234'
  • Related