
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to create Python dictionary from JSON input?
You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content
{ "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }
You can load it in your python program and loop over its keys in the following way:
import json f = open('data.json') data = json.load(f) f.close()
# Now you can use data as a normal dict:
for (k, v) in data.items(): print("Key: " + k) print("Value: " + str(v))
This will give the output:
Key: id Value: file Key: value Value: File Key: popup Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
- Related Articles
- How to create Python dictionary from the value of another dictionary?
- How to parse JSON input using Python?
- How to create a Python dictionary from text file?
- In Python how to create dictionary from two lists?
- How to print Python dictionary into JSON format?
- How to create a Pandas series from a python dictionary?
- Python – Create dictionary from the list
- How to create nested Python dictionary?
- How I can create Python class from JSON object?
- How to create Python dictionary from list of keys and values?
- Python Program – Create dictionary from the list
- Python program to create a dictionary from a string
- How to create a dictionary in Python?
- How to create a Python dictionary from an object's fields?
- How to create Python dictionary by enumerate function?

Advertisements