Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a list and dictionary in Python?

1) How we can combine a dict with list and return the result as JSON? Have tried to combine list_1(dict) and list_2(list), but getting error. Also, after converting them to strings can combine but could not decode back to JSON format(as expected result below).

2) Also, how to replace a value within JSON and maintain it as JSON?

list_1 = [{'title': 'NEWBOOK', 'downloads': '4', 'views': '88'}]

list_2 = {'title': 'MASTERMIND', 'downloads': '16', 'views': '156'}

list_3 = {
       'a': 'b',
       'c': 'd',
       'e': [{
         'f': 'g',
         'l': 'm'
         }]
       }

Script which I have tried as below.

combine = list_1 +  list_2



for z in list_3['e']:

list_3 = list_3.replace(z, combine)

Expected_json = json.dumps(list_3)

print(list_3)

Error1:

combine = list_1 +  list_2

TypeError: can only concatenate list (not "dict") to list

Error2:

list_3 = list_3.replace(z, combine)

AttributeError: 'dict' object has no attribute 'replace'

Expected result:

list_3 = {
    "a": "b",
    "c": "d",
    "e": [{
            "f": "g",
            "l": "m"
        },
        {
            "title": "NEWBOOK",
            "downloads": "4",
            "views": "88"
        },
        {
            "title": "MASTERMIND",
            "downloads": "16",
            "views": "156"
        }
    ]
}
like image 520
PKU Avatar asked Jan 24 '26 12:01

PKU


1 Answers

Simply append to the list in the dictionary

list_3['e'].append(list_2)
list_3['e'].append(list_1[0])
print(list_3)

{
    'a':
    'b',
    'c':
    'd',
    'e': [{
        'f': 'g',
        'l': 'm'
    }, {
        'title': 'MASTERMIND',
        'downloads': '16',
        'views': '156'
    }, {
        'title': 'NEWBOOK',
        'downloads': '4',
        'views': '88'
    }]
}
like image 115
johnashu Avatar answered Jan 27 '26 01:01

johnashu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!