2016/11/23

Python list operations examples

Here is the sample code for displaying, adding, removing contents from a list in Python.


Python Script

 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
import json
 
my_dictionary = {"state_sensors":
 [{"id":"1", "power":"on", "trigger":"no"},
  {"id":"2", "power":"off", "trigger":"no"},
  {"id":"3", "power":"on", "trigger":"no"},
  {"id":"4", "power":"off", "trigger":"no"},
  {"id":"5", "power":"on", "trigger":"yes"},
 ],
 "temperature_sensor":
 [{"id":"1", "temp":"30.5"},
  {"id":"2", "temp":"50.85"}
 ],
 "current_sensor":
 [{"id":"1", "current":"10.1"},
  {"id":"2", "current":"20.5"}
 ],
 "time_stamp": "2016/11/23, 09:30AM"
}

# Accessing the content in the my_dictionary object
print("**Object**")
print(my_dictionary["time_stamp"])

print(my_dictionary["state_sensors"][4])
print(my_dictionary["state_sensors"][4]["trigger"])

print(my_dictionary["temperature_sensor"][1])
print(my_dictionary["temperature_sensor"][1]["temp"])

print(my_dictionary["current_sensor"][1])
print(my_dictionary["current_sensor"][1]["current"])

# Add a new element to the end of "state_sensors"
print("Add a new element to the end of state_sensors")
my_dictionary["state_sensors"].append({"id":"6", "power":"yes", "trigger":"yes"})
print(my_dictionary["state_sensors"])

# Remove an element from "state_sensors"
print("")
print("Remove an element from state_sensors")
my_dictionary["state_sensors"].pop(2)
print(my_dictionary["state_sensors"])

# Create a new element to be added into my_dictionary
print("")
print("Create a new element")
tmp = {}
tmp["id"] = "7"
tmp["power"] = "yes"
tmp["trigger"] = "yes"
print(tmp)

# Add the newly created element to the end of "state_sensors"
print("")
print("Add the newly created element to the end of state_sensors")
my_dictionary["state_sensors"].append(tmp)
print(my_dictionary["state_sensors"])

Result


References:

Add key to a dictionary in Python?
http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python

How to append in a json file in Python?
http://stackoverflow.com/questions/18980039/how-to-append-in-a-json-file-in-python

Adding a new array element to a JSON object
http://stackoverflow.com/questions/18884840/adding-a-new-array-element-to-a-json-object

Python List Examples – Insert, Append, Length, Index, Remove, Pop
http://www.thegeekstuff.com/2013/06/python-list/?utm_source=feedly

No comments:

Post a Comment