Home > Software engineering >  How Can I "append" dictionaries into a nested dictionary
How Can I "append" dictionaries into a nested dictionary

Time:06-02

I have tried to tried to seperate each dictionary inside the list names to their own category depending on the first letter of the name. I'm pretty new to coding and I have tried a to use other functions like update but I have been unsuccessful in achieving the end result. I don't know how to append dictionaries inside a nested dictionary.

names = [{"name":"alpha"}, {"name":"apple"}, {"name":"bravo"}, {"name":"charlie"}, {"name":"chucky"}]

foo = {
    "a" : {},
    "b" : {},
    "c" : {}
}

End result should be:

foo = {
    "a" : {
        {"name":"alpha"},
        {"name":"apple"}
    },
    "b" : {
        {"name":"bravo"}
    },
    "c" : {
        {"name":"charlie"},
        {"name":"chucky"}
    }
}

CodePudding user response:

Dictionaries are key,value pairs so your desired output isn't possible.

Also dictionary keys must be unique, so calling update on a dictionary using a key that already exists will simply overwrite the value.

It sounds like what you want is to have a list as the nested structure like this:

foo = {}
for item in names:
    char = item["name"][0]
    try:
        foo[char].append(item)
    except KeyError:
        foo[char] = [item]
print(foo)

output

foo = {
    "a" : [
        {"name":"alpha"},
        {"name":"apple"}
    ],
    "b" : [
        {"name":"bravo"}
    ],
    "c" : [
        {"name":"charlie"},
        {"name":"chucky"}
    ]
}

CodePudding user response:

Your goal is this:

foo = { # dict
    "a" : [ # list
        {"name":"alpha"}, # dict
        {"name":"apple"}
    ],
    "b" : [
        {"name":"bravo"}
    ],
    "c" : [
        {"name":"charlie"},
        {"name":"chucky"}
    ]
}

Hint: iterate item in names and update/append foo[ item[0] ], item[0] is the first letter (item['name'][0] to be exact).

CodePudding user response:


    #try this

    names = [{"name":"alpha"}, {"name":"apple"}, {"name":"bravo"}, 
    {"name":"charlie"}, {"name":"chucky"}]

    foo = {
    "a" : {},
    "b" : {},
    "c" : {}
    }

    for keys in foo.keys():
      lists=[]
      for name in names:
        for key,val in name.items():
            if val[0].lower()==keys.lower():
                lists.append(name)
      foo[keys]=lists
    print(foo)

**bro you doing some mistake here :

   "a" : {
        {"name":"alpha"},
        {"name":"apple"}
    }

-dict always accept key and value pair not only value because it's happen,if in future you try to append dict without key so always use list not dict**

    foo = {
           "a" : [
                  {"name":"alpha"},
                  {"name":"apple"}
                 ],
           "b" : [
                  {"name":"bravo"}
                 ],
           "c" : [
                  {"name":"charlie"},
                  {"name":"chucky"}
                 ]
          }

CodePudding user response:

The below dictionary is invalid as you cannot have dictionaries separated by commas as the sole contents of another dictionary. A dictionary is supposed to contain key, value pairs.

foo = {
    "a" : {
        {"name":"alpha"},
        {"name":"apple"}
    },
    "b" : {
        {"name":"bravo"}
    },
    "c" : {
        {"name":"charlie"},
        {"name":"chucky"}
    }
}

For example in the below key, value pair a is the key, it is fine till this part. The part {{"name":"alpha"},{"name":"apple"}} is the problem where you have dictionaries separated by commas within another dictionary, this will result in error TypeError: unhashable type: 'dict'

"a" : {
        {"name":"alpha"},
        {"name":"apple"}
    },

However, you can have a list of dictionaries as the value of a key.

You can use the below method to create one.

import json

names = [{"name":"alpha"}, {"name":"apple"}, {"name":"bravo"}, {"name":"charlie"}, {"name":"chucky"}]

foo = {}

for item_dict in names:
    val = item_dict["name"]
    foo.setdefault(val[0], []).append(item_dict)

print(json.dumps(foo, indent=2))

This will output:

{
  "a": [
    {
      "name": "alpha"
    },
    {
      "name": "apple"
    }
  ],
  "b": [
    {
      "name": "bravo"
    }
  ],
  "c": [
    {
      "name": "charlie"
    },
    {
      "name": "chucky"
    }
  ]
}
  • Related