-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlearningjson.py
More file actions
225 lines (187 loc) · 5.63 KB
/
Copy pathlearningjson.py
File metadata and controls
225 lines (187 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 10:32:36 2020
@author: lammi
"""
# =============================================================================
# Learning JSON and Dictionary Manipulation
# =============================================================================
from pprint import pprint #Uncomment line 63
import json
def basic_json():
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["name"])
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
} # different from ''
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
# Convert Python objects into JSON strings, and print the values:
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
# Convert a Python object containing all the legal data types:
x1 = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x1))
# use . and a space to separate objects, and a space,
# a = and a space to separate keys from their values:
print(json.dumps(x1, indent=4))
print(json.dumps(x1, indent=4, separators=(". ", " = ")))
# sort the result alphabetically by keys:
print(json.dumps(x1, indent=4, sort_keys=True))
return x,y,x1
def definition():
# Opening JSON file
f = open('data.json',)
# returns JSON object as a dictionary
data = json.load(f)
# Iterating through the json list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
def json_to_file():
# Writing JSON to a File
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
print (data)
return data
def dict_manipulation():
"""
You are here: Home / Dictionary / Dictionary Manipulation in Python
Dictionary Manipulation in Python
Last Updated: August 26, 2020
Overview
A dictionary is a collection of key-value pairs.
A dictionary is a set of key:value pairs.
All keys in a dictionary must be unique.
In a dictionary, a key and its value are separated by a colon.
The key, value pairs are separated with commas.
The key & value pairs are listed between curly brackets ” { } ”
We query the dictionary using square brackets ” [ ] ”
"""
# Create an empty dictionary
months = {}
months = { 1 : "January",
2 : "February",
3 : "March",
4 : "April",
5 : "May",
6 : "June",
7 : "July",
8 : "August",
9 : "September",
10 : "October",
11 : "November",
12 : "December" }
print(months)
print(type(months))
# Print all keys
print ("The dictionary contains the following keys: ", months.keys())
# Get a value out of a dictionary
whichMonth = months[1]
print ('Get value', whichMonth)
# Delete an element from a dictionary
del(months[5])
print ('Delete', months.keys())
# Update an element of a dictionary
months[1] = "Jan"
print (months)
# Sort
sortedkeys = months.keys()
print ('Sorting', sortedkeys)
# Iterate over keys
for key in months:
print ('Loops over keys', key, months[key])
# Iterate over (key, value) pairs
for key, value in months.items():
print ('Pair', key, value)
print ("The entries in the dictionary are:")
for item in months.keys():
print ("months[ ", item, " ] = ", months[ item ])
return months
def combine_list_dict():
"Combining List and Dictionary"
# List of dictionaries
customers = [{"uid":1,"name":"John"},
{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
print ('origin', customers)
print ('Type', type(customers))
# Print the uid and name of each customer
for x in customers:
print (x["uid"], x["name"])
# Modify an entry
customers[2]["name"]="charlie"
print ('Modify', customers[2])
# Add a new field to each entry
for x in customers:
x["password"]="123456" # any initial value
print ('Add for all', customers)
# Delete a field
del customers[1]
print ('Delete a field', customers)
# This will delete id field of each entry.
for x in customers:
del (x["uid"], x["password"])
print ('Delete 2 keys', customers)
return customers
def listToDict(lstA, lstB):
zippedLst = zip(lstA, lstB)
op = dict(zippedLst)
return op
def main():
# basic_json()
# json_to_file()
# dict_manipulation()
# combine_list_dict()
# lstStr = ['millie', 'caleb', 'finn', 'sadie', 'noah']
# lstInt = [11, 21, 19, 29, 46]
# print(listToDict(lstStr, lstInt))
# listToDict(lstStr, lstInt)
if __name__ == "__main__":
main()