简体   繁体   中英

how do i make a nested dictionary in python?

I'm trying to make an API that fetches memes from Reddit and I am stuck at creating JSON data with nested dictionaries. I have the following dictionaries and I want to merge them together. How do I go about it?

{
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
}

and the other one as follows

{
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}

I want to make something like the following in python

{
{
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
},
{
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}
}

As others pointed out the result is not a valid json or dict.

You need a key for the dict object:

a = {
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
}

b = {
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}

res = {"items": [a, b]}

print(res)

Output:

{'items': [{'author': 'Mizanur1214', 'nsfw': None, 'subreddit': 'dankmemes', 'title': 'They do be like that', 'upvotes': 33302, 'url': 'https://i.imgur.com/xZpJFQU.jpg'}, {'author': 'Kristis1', 'nsfw': None, 'subreddit': 'me_irl', 'title': 'me irl', 'upvotes': 1941, 'url': 'https://i.redd.it/u2qesppixhh61.jpg'}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM