CodesJava

Easy learning with example program codes

Python Dictionary


Python Dictionary:

A dictionary is a collection or an associative array which is used to store various types of data.

Features of Python Dictionaries:

  • They are unordered and changeable.
  • They are written within curly brackets.
  • They can store multiple types of data.
  • They are mutable. Thus, the current values in the dictionary can be modified.
  • Keys are immutable. Thus, it can not be modified.
  • Python Dictionaries supports various operations.
  • The complete pair of key and value is called as a dictionary item.
  • The key passed in each dictionary item must be unique.
  • The key and the value is separated by a colon(:).
  • Items are separated from each other by a comma(,).
  • Value in a dictionary can be accessed by its key.

Python Dictionaries Methods:

METHODS USES
clear() To remove all the elements from the dictionary.
cmp() To compare two dictionaries.
copy() To get a copy of the dictionary.
fromkeys() To get a dictionary with the specified keys and values.
get() To get the value of the specified key.
items() To get a list containing the a tuple for each key value pair.
¬†keys() To get a list containing the dictionary’s keys.
len() To get the number of items in a dictionary.
pop() To get the element with the specified key.
 popitem() To remove the last key-value pair.
setdefault() To get the value of the specified key. If the key does not exist: insert the key, with the specified value.
str() To get the string representation of a dictionary.
update() To update the dictionary with the specified key-value pairs.
values() To get a list of all the values in the dictionary.

Example:

a =  { "1": "python",
"2": "java",
  "3": "php",
   "4": "HTML",
    "5": "javascript",
     "6": "CSS",
      "7": "Bootstrap"}
print "\n"
print "Dictionary is:"
print a
print "\n"
 
print "Get the value of the key 1."
print(a["1"])
print "\n"
 
print "Get the total length."
print(len(a))
print "\n"
 
print "Delete the item."
del a["5"]
print a
print "\n"
 
print "Replace a value."
a["3"] = "jQuery"
print a
print "\n"
 
print "Add a value."
a["9"] = "C"
print a
print "\n"

Output:

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki