• 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

Advanced SQL Injection

Adobe Interview Questions 8 month Exp

Calculate price of parking from parking start end time prices

Check if an array has duplicate numbers in O(n) time and O(1) space

Printing each word reverse in string

Find an index i such that Arr [i] = i in array of n distinct integers sorted in ascending order.

Coin Collection Dynamic Programming

Spanning Tree

Minimum insertions to form a palindrome

Hackerearth : Counting Subarrays

Longest Increasing Subsequence

Maximum difference between two elements s.t larger element appears after the smaller number

Find position of the only set bit

C++ OOPs Part2

Find two non repeating elements in an array of repeating elements

Naurki.com Security Breach

The greedy coins game Dynamic Programming

How Radix sort works

Diagonal Traversal of Binary Tree

Find the smallest window in a string containing all characters of another string

Singly linked list

Maximum size of square sub matrix with all 1’s in a binary matrix

Sequence Finder Dynamic Programming

SAP Hiring Off-Campus General Aptitude

Code Chef PRGIFT Solution

There are N nuts and N bolts, u have to find all the pairs of nuts and bolts in minimum no. of iteration

Cisco Hiring Event 21st – 22nd Feb 2015

System Design: Designing a LLD for Hotel Booking

Check a String is SUBSEQUENCE of another String Find Minimum length for that ( DNA Matching )

Stock Buy Sell to Maximize Profit

Copyright © 2025 · Genesis Framework · WordPress · Log in