• 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

Right view of Binary tree

Microsoft BING Interview Experience

DFS (Depth First Search)

strtok()

Coin Collection Dynamic Programming

Find min element in Sorted Rotated Array (Without Duplicates)

Subset Sum Problem Dynamic programming

Interfaces in C++ (Abstract Classes in C++)

Maximum occurred Smallest integer in n ranges

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

Closed Parentheses checker

Python List

1014 Practice Question of New GRE – Princeton

Binary Tree Isomorphic to each other

SAP Interview Questions

Binary Tree in Java

Stock Buy Sell to Maximize Profit

Handle duplicates in Binary Search Tree

Level order traversal in Spiral form

Convert Decimal to Roman numbers / Romanizer HackerEarth Code

Find if two rectangles overlap

robot standing at first cell of an M*N matrix. It can move only in two directions, right and down. In how many ways, it can reach to the last cell i.e. (M, N) Code it

SAP Off Campus Hiring_ March 2015 Sample Questions

25 horses 5 tracks Find 3 fastest puzzle

Amazon Interview On-Campus For Internship – 1

Get Minimum element in O(1) from input numbers or Stack

Leetcode: Edit Distance

Trapping Rain Water

In Given LinkedList Divide LL in N Sub parts and delete first K nodes of each part

TicTacToe Game As Asked in Flipkart

Copyright © 2025 · Genesis Framework · WordPress · Log in