• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Python Dictionaries

February 25, 2015 by Dhaval Dave

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

Each key is separated from its value by a colon (:) , the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];

When the above code is executed, it produces the following result:

dict['Name']:  Zara
dict['Age']:  7

Updating Dictionary:

You can update a dictionary by adding a new entry or item (i.e., a key-value pair), modifying an existing entry, or deleting an existing entry as shown below in the simple example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry


print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];

When the above code is executed, it produces the following result:

dict['Age']:  8
dict['School']:  DPS School

Delete Dictionary Elements:

del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

Dictionary cmp() Method : This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1 if dict1 > dic2.

dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" %  cmp (dict1, dict2)
print "Return Value : %d" %  cmp (dict2, dict3)
print "Return Value : %d" %  cmp (dict1, dict4)

When we run above program, it produces following result:

Return Value : -1
Return Value : 1
Return Value : 0

 Dictionary len() Method : it gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

Dictionary str() Method :  produces a printable string representation of a dictionary.

dict = {'Name': 'Zara', 'Age': 7};
print "Equivalent String : %s" % str (dict)

When the above code is executed, it produces the following result:

Equivalent String : {'Age': 7, 'Name': 'Zara'}

Dictionary has_key() Method :  returns true if a given key is available in the dictionary, otherwise it returns a false.

dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" %  dict.has_key('Age')
print "Value : %s" %  dict.has_key('Sex')

When the above code is executed, it produces the following result:

Value : True
Value : False

Dictionary get() Method returns a value for the given key. If key is not available then returns default value None.

dict = {'Name': 'Zara', 'Age': 27}

print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Sex', "Never")

When the above code is executed, it produces the following result:

Value : 27
Value : Never

Dictionary update() Method : adds dictionary dict2’s key-values pairs in to dict. This function does not return anything.

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }

dict.update(dict2)
print "Value : %s" %  dict

When the above code is executed, it produces the following result:

Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}

Dictionary values() Method : returns a list of all the values available in a given dictionary.

dict = {‘Name’: ‘Zara’, ‘Age’: 7}

print "Value : %s" %  dict.values()

When the above code is executed, it produces the following result:

Value : [7, 'Zara']

asd

Similar Articles

Filed Under: problem Tagged With: python

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

C++ OOPs Part1

Generate largest number arranging a no. of given non negative integer numbers

Flipkart SDET Interview Experience

Top 10 Interviews Techniqes for Campus Interview in IIT NIT BITS for MTech

Binary Tree in Java

25 horses 5 tracks Find 3 fastest puzzle

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

TicTacToe Game As Asked in Flipkart

Find the kth number with prime factors 3, 5 and 7

Inorder and Preorder traversals of a Binary Tree given. Output the Postorder traversal of it.

Print vertical sum of all the axis in the given binary tree

Find Percentage of Words matching in Two Strings

Linked List V/S Binary Search Tree

simple sql injection

Stickler thief

Find next greater number with same set of digits

Number of Islands BFS/DFS

Given a string, find the first character which is non-repetitive

Amazon Interview On-Campus For Internship – 1

Given Set of words or A String find whether chain is possible from these words or not

Possible sizes of bus to carry n groups of friends

Find the number ABCD such that when multipled by 4 gives DCBA.

SAP Off Campus Hiring_ March 2015 Computer Skills

Sequence Finder Dynamic Programming

Coin Collection Dynamic Programming

K’th Largest Element in BST when modification to BST is not allowed

Introduction To Number Theory ( Part 1 )

Handle duplicates in Binary Search Tree

Serialise Deserialise N-ary Tree

Find if two rectangles overlap

Copyright © 2025 · Genesis Framework · WordPress · Log in