List of dictionaries, in a dictionary - in Python

12,978

Solution 1

Example, that you've posted is not a valid python code, I could only imagine that you're trying to do something like this:

self.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]

this way self.rules is a dictionary of a list of a dictionary of a dictionary. I bet there is more sane way to do this.

Solution 2

rules = {}
failure = 'hard_failure'
rules[failure] = []
for row in rows:
  #this is what people are referring to below.  You left out the addition of the    dictionary structure to the list.
  rules[failure][row[0]] = {} 
  rules[failure][row[0]]['type 1'] = row[1]
  rules[failure][row[0]]['type 2'] = row[2]

This is what I created based on how I understood the questions. I wasn't sure what to call the 'f_expr' and 'c_expr' since you never mention where you get those but I assume they are already know column names in a resultset or structure of some sort.

Just keep adding to the structure as you go.

Share:
12,978
Terry Felkrow
Author by

Terry Felkrow

Python convert.

Updated on June 04, 2022

Comments

  • Terry Felkrow
    Terry Felkrow almost 2 years

    I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want)

    I basically need a dictionary, with a dictionary of dictionaries created within the loop. At the beginning the structure is completely blank.

    structure sample (please note, I want to create an array that has this structure in the code!)

    RULE = {
         'hard_failure': {
            4514 : {
               'f_expr' = 'ABC',
               'c_expr' = 'XF0',
         }
        }
       }
    

    pseudo code that needs to create this:

    ...
    self.rules = {}
    for row in rows:
         a = 'hard_failure'
         b = row[0] # 4514
         c = row[1] # ABC
         d = row[2] # XF0
         # Universe collapse right after
         self.rules = ????
    ...   
    

    The code above is obviously not working since I dont know how to do it!

  • Peter Hansen
    Peter Hansen over 14 years
    Correct way to handle this on Stack Overflow is to edit your question to clarify the whole thing, rather than putting in an "answer" that may not be an answer. If this is really an answer, then accept it by clicking on the checkmark icon to the left. Otherwise people coming here later haven't got a clue what you're up to.