Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22853

IslandT: Python Tutorial — Chapter 8

$
0
0

In this chapter let us look at the python dictionary collection object. Python dictionary object has both key and value pair and it is used to store data. The key of the python dictionary is not duplicatable.

In order to create the dictionary’s key and value pair, you need a key that links to a value (data) like below:-

power = {
  "station1": 200,
  "station2": 300,
  "location": "New York"
}

In order to retrieve the value from a dictionary, used its key as follows:-

power["station1"]

In order to change the value of a key, all you need to do is as follows:-

power['station1'] = 500

Example: Loop and print the key and value pairs within the above dictionary.

for key, value in power.items():
   print(key + " : " + str(value))
station1 : 200
station2 : 300
location : New York

Example: Loop and print only the values of the above dictionary.

for value in power.values():
   print(value)

Example: Get an item from the key.

a = power.get("station1") # 200

Example: Get rid of one item in the above dictionary.

print(power.pop("station1"))
    print(power)
200
{'station2': 300, 'location': 'New York'}

Example: Put more items into the above dictionary.

power['station3'] = 600

Example: Clear all the key and value pairs in the above dictionary.

power.clear()

Example: Print the keys of the above dictionary.

for key in power.keys():
   print(key)

Example: Get the key and value pair of the last item in the above dictionary.

power.popitem()

Example: Make and assign a copy of the above dictionary to another dictionary.

power1 = power.copy()

There are still a lot of dictionary methods I have not yet covered and you can learn all of them on the official Python document’s page.


Viewing all articles
Browse latest Browse all 22853

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>