Python - dictionary


Dictionary is defined as a key-value based data structure where each key maps to some value.

It is used for defining a data structure where we want to organize/group data by creating a meaningful relationship between keys( eg. name, age, branch) and their values( eg. 'Robert Prince', 22, "Mechanical engineering" ).

Interactive mode programming is a best way to start or have some basic knowledge of Python concepts. So here I'm starting with that.



  """
      created_at       : 14 Feb 2017.
      updated_at       : 14 Feb 2017.
      aim of script    : To understand the concept of dictionary in Python.
      coded by         : Rishikesh Agrawani.
      Python version   : 2.7.12
  """
  

 #Interactive mode programming - #1

>>> d = {"city": "Bangalore", "state":"Karnataka", "country":"India"} #d is a dictionary with 3 items >>> d["city"] #printing 1st item 'Bangalore' >>> >>> d["state"] #printing state 'Karnataka' >>> >>> d["country"] #printing country 'India' >>> >>> print d #printing whole dictionary {'city': 'Bangalore', 'state': 'Karnataka', 'country': 'India'} >>>

 #Interactive mode programming - #2

>>> d = {"city": "Bangalore", "state":"Karnataka", "country":"India"} >>> >>> d.values() ['Bangalore', 'Karnataka', 'India'] >>> >>> d.keys() ['city', 'state', 'country'] >>>

 #Interactive mode programming - #3

>>> d = {"city": "Bangalore", "state":"Karnataka", "country":"India"} >>> print d {'city': 'Bangalore', 'state': 'Karnataka', 'country': 'India'} >>> >>> import json #importing json module >>> pretty_d = json.dumps(d) >>> print pretty_d {"city": "Bangalore", "state": "Karnataka", "country": "India"} >>> >>> pretty_d2 = json.dumps(d,indent=4) >>> print pretty_d2 { "city": "Bangalore", "state": "Karnataka", "country": "India" } >>> >>> pretty_d3 = json.dumps(d,indent=6) >>> print pretty_d3 { "city": "Bangalore", "state": "Karnataka", "country": "India" } >>>

 #Interactive mode programming - #4

>>> import json >>> d = {"city": "Bangalore", "state":"Karnataka", "country":"India"} >>> >>> json.dumps(d) '{"city": "Bangalore", "state": "Karnataka", "country": "India"}' >>> >>> json.dumps(d, indent=3) '{\n "city": "Bangalore", \n "state": "Karnataka", \n "country": "India"\n}' >>> >>> print json.dumps(d, indent=3) { "city": "Bangalore", "state": "Karnataka", "country": "India" } >>>

 #Interactive mode programming - #5

>>> import json >>> d = {"city": "Bangalore", "state":"Karnataka", "country":"India"} >>> >>> print json.dumps(d, indent=6, sort_keys=True) #printing dictionary in ascending order of keys { "city": "Bangalore", "country": "India", "state": "Karnataka" } >>>

 #Interactive mode programming - #6

>>> self = { 'name':'Grimmy Heldon', ... 'age' :20, ... 'friends':['Malinikesh','Smarika','Manjoosa','Dolly'], ... 'siblings':[{'name':'Price Heldon','age':18},{'name':'Cuty Heldon','age':1}], ... 'is_active':True ... } >>> >>> print self {'is_active': True, 'siblings': [{'age': 18, 'name': 'Price Heldon'}, {'age': 1, 'name': 'Cuty Heldon'}], 'age': 20, 'friends': ['Malinikesh', 'Smarika', 'Manjoosa', 'Dolly'], 'name': 'Grimmy Heldon'} >>> >>> import json >>> print json.dumps(self) {"is_active": true, "siblings": [{"age": 18, "name": "Price Heldon"}, {"age": 1, "name": "Cuty Heldon"}], "age": 20, "friends": ["Malinikesh", "Smarika", "Manjoosa", "Dolly"], "name": "Grimmy Heldon"} >>> >>> print json.dumps(self,indent=5) { "is_active": true, "siblings": [ { "age": 18, "name": "Price Heldon" }, { "age": 1, "name": "Cuty Heldon" } ], "age": 20, "friends": [ "Malinikesh", "Smarika", "Manjoosa", "Dolly" ], "name": "Grimmy Heldon" } >>> >>> print json.dumps(self,indent=5,sort_keys=True) { "age": 20, "friends": [ "Malinikesh", "Smarika", "Manjoosa", "Dolly" ], "is_active": true, "name": "Grimmy Heldon", "siblings": [ { "age": 18, "name": "Price Heldon" }, { "age": 1, "name": "Cuty Heldon" } ] } >>> >>> print json.dumps(self,indent=5,separators=['....','****']) { "is_active"****true.... "siblings"****[ { "age"****18.... "name"****"Price Heldon" }.... { "age"****1.... "name"****"Cuty Heldon" } ].... "age"****20.... "friends"****[ "Malinikesh".... "Smarika".... "Manjoosa".... "Dolly" ].... "name"****"Grimmy Heldon" } >>> >>> print json.dumps(self,indent=5,separators=['\*/','|*|']) { "is_active"|*|true\*/ "siblings"|*|[ { "age"|*|18\*/ "name"|*|"Price Heldon" }\*/ { "age"|*|1\*/ "name"|*|"Cuty Heldon" } ]\*/ "age"|*|20\*/ "friends"|*|[ "Malinikesh"\*/ "Smarika"\*/ "Manjoosa"\*/ "Dolly" ]\*/ "name"|*|"Grimmy Heldon" } >>> >>> print json.dumps(self,indent=5,separators=['\*/',' ==> ']) { "is_active" ==> true\*/ "siblings" ==> [ { "age" ==> 18\*/ "name" ==> "Price Heldon" }\*/ { "age" ==> 1\*/ "name" ==> "Cuty Heldon" } ]\*/ "age" ==> 20\*/ "friends" ==> [ "Malinikesh"\*/ "Smarika"\*/ "Manjoosa"\*/ "Dolly" ]\*/ "name" ==> "Grimmy Heldon" } >>> >>> print json.dumps(self,indent=15) { "is_active": true, "siblings": [ { "age": 18, "name": "Price Heldon" }, { "age": 1, "name": "Cuty Heldon" } ], "age": 20, "friends": [ "Malinikesh", "Smarika", "Manjoosa", "Dolly" ], "name": "Grimmy Heldon" } >>>

A simple task for you beginners » Write a pyscript to print a list of all the keys of a dictionary including the nested ones.
The following examples will clarify your concepts.
I've used long variable names for making it undestandable for you.

 #Example - 1

employee = {"name" : "Jordon Smith", "age" : 24, "monthly_salary": 200000.67} print employee["name"] #Jordon Smith print employee["age"] #24 print employee["monthly_salary"] #200000.67 print employee #{'age': 24, 'name': 'Jordon Smith', 'monthly_salary': 200000.67} print employee.values() #[24, 'Jordon Smith', 200000.67] print employee.keys() #['age', 'name', 'monthly_salary'] print employee

 #Example - 2

student_details = {"name" : "Robert James", "age" : 55, "degree" : "BTech", "branch" : "CSE", "university" : "IIT, Kanpur"} print student_details #Printing whole dictionary print student_details["name"] #Robert James print student_details['age'] #55 print student_details['degree'] #BTech keys = student_details.keys() #creating list of keys for key in keys: #iterating through created list of keys print key," ==> ",student_details[key] #printing key and value referenced by it

 #Example - 3 (Pretty printing dictionary)

import json #importing json module student_details = {"name" : "Robert James", "age" : 55, "degree" : "BTech", "branch" : "CSE"} #Defining a dictionary pretty_format_details = json.dumps(student_details,indent=4) #dumps() function returns the string #representation of dictionary based on the keyworded arguments(if provided) print pretty_format_details

 #Example - 4 (Pretty printing dictionary in sorted keys order)

import json #importing json module student_details = {"name" : "Robert James", "age" : 55, "degree" : "BTech", "branch" : "CSE"} #Defining a dictionary pretty_format_key_sorted_details = json.dumps(student_details,indent=4,sort_keys=True) print pretty_format_key_sorted_details

 #Example- 5

"""Designing a function that takes 1 dictionary as an argument & returns a list 2 items. First item will be a tuple containing all the keys & second item will be a list of values.""" def key_value_separator(details): return [tuple(details.keys()), details.values()] my_details = { "name": "Rishikesh Agrawani", \ #Dictionary spanned in 4 lines "age" : 24, \ "branch" : "CSE" \ } print key_value_separator(my_details) #[('age', 'name', 'branch'), [24, 'Rishikesh Agrawani', 'CSE']]