create dictionary based on two lists

Asked

Viewed 503 times

1

I have a list of items and a list of submenus (imagine a menu), because then, I would like to create a dictionary separating the items by the key of your menu. I couldn’t develop a logic that worked for this problem. Follow code and an example draft of a desired output. thank you.

items = [('a', 1),('b', 1),('c', 2)]
submenu = [('x', 1), ('y', 2)]
dictry = []

for i in range(len(items)):
    d = {}
    d['id_item'] = items[0][0]
    d['id_submenu'] = items[0][1]
    dictry.append(d)
    items.pop(0)

print(dictry)

#SaidaEsperada#
{
    "Menu": [
        {
            "X": [
                {
                    "id_item": "a",
                    "id_submenu": 1
                },
                {
                    "id_item": "b",
                    "id_submenu": 1
                }
            ]
        },
        {
            "Y": [
                {
                    "id_item": "c",
                    "id_submenu": 2
                }

            ]
        }

    ]
}
  • Rodolfo, this expected output that you put in the question is not valid, try to create a valid dictionary, because with this structure you can not understand how the output really should be.

  • @user140828 I edited, but basically I need to consolidate the items based on their corresponding submenu. see if you understand now please. thank you

1 answer

1

I don’t quite understand what those "X" and "Y" values mean, but it would be something like this that you want ?

import json

items_list = ["frango a passarinho","pizza de calabresa"]
id_item_list = ["ID_i234","ID_i566"]
id_submenu = ["ID_s1923","ID_s2341"]

items = zip(items_list,id_item_list,id_submenu)

dic = {"Menu":{}}

for item in items:
    dic["Menu"][item[0]] = {}
    dic["Menu"][item[0]]["id_item_list"] = item[1]
    dic["Menu"][item[0]]["id_submenu"] = item[2]

print(json.dumps(dic,indent=4))

I need to better understand what exactly you want. For example, what would be this "id_submenu", whether this name is fixed or if it is some variable, etc.

  • Fantastic, I’ll try to apply your guidance to my problem, I think it works. But just to answer your question: in the "submenu" list I have the X submenus with id 1 and the Y submenu with submenu 2. in the list of items, I have the items a, b, c following with the "foreign key" that "links" the submenu. Example, the chicken the bird is to submenu X:1 and the coca cola is to submenu Y:2. which would look like this X:1 { chicken the bird Y:2 { coca cola basically what I need is to separate the items according to the submen code..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.