Home>

Hello everyone! I'm just starting to learn Python, so I'm fighting for the 3rd day (

There is a list, something like this:

list= [['user', "data1"],
['last_name', 'data2'],
['first_name', 'data3'],
['address', 'data4'],
['email', 'data5'],
['email', 'data6'],
['address', 'data7'],
['address', 'data8'],
['email', 'data9'],
['some', 'data10'],
['more', 'data11']]

How to combine by keys? (ps they may be different). Ultimately, I would like to get json of the form:

id= id
[
    {
        "id": {
            "user": 'data1',
            "last_name": 'data2',
            "first_name": "data3",
            "address": {
                0: 'data4',
                1: 'data7',
                2: 'data8'
            },
            "email": {
                0: 'data5',
                1: 'data6',
                2: 'data9'
            },
            "some": 'data9',
            "more": 'data10'
        }
    }
]

Tried like this:

resultdict= {}
for key, value in list:
    try:
        resultdict [key] += value
    except KeyError:
        resultdict [key]= value

But this only adds a value to the key, but a list of values ​​is needed ..

????

  • Answer # 1

    Keys are added to the dictionary by the list. If the key is new, then a string is added to the value. If the key is repeated, then the value is converted into a dictionary.

    dct= {}
    for k, v in list:
        if k not in dct:
            dct [k]= v
        else:
            if type (dct [k])!= dict:
                dct [k]= {0: dct [k]}
            dct [k] [len (dct [k])]= v
    import json
    print (json.dumps (dct, indent= 4))
    

    Conclusion:

    {
        "user": "data1",
        "last_name": "data2",
        "first_name": "data3",
        "address": {
            "0": "data4",
            "1": "data7",
            "2": "data8"
        },
        "email": {
            "0": "data5",
            "1": "data6",
            "2": "data9"
        },
        "some": "data10",
        "more": "data11"
    }
    
  • Answer # 2

    Keys are added to the dictionary by the list. If the key is new, then a string is added to the value. If the key is repeated, then the value is converted into a dictionary.

    dct= {}
    for k, v in list:
        if k not in dct:
            dct [k]= v
        else:
            if type (dct [k])!= dict:
                dct [k]= {0: dct [k]}
            dct [k] [len (dct [k])]= v
    import json
    print (json.dumps (dct, indent= 4))
    

    Conclusion:

    {
        "user": "data1",
        "last_name": "data2",
        "first_name": "data3",
        "address": {
            "0": "data4",
            "1": "data7",
            "2": "data8"
        },
        "email": {
            "0": "data5",
            "1": "data6",
            "2": "data9"
        },
        "some": "data10",
        "more": "data11"
    }