• 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

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

‘N’ Story Building, with 1,2,3 steps how many ways can a person reach top of building.

CodeChef Code SGARDEN

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

Implement LRU Cache

Maximum of all subarrays of size k

Check Binary Tree is Binary Search Tree or not

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

Get K Max and Delete K Max in stream of incoming integers

Edit Distance ( Dynamic Programming )

Urban Ladder Written Test.

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

Printing each word reverse in string

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

Daughter’s Age VeryGood Puzzle

Knight Tour Problem (Graph – Breadth First Search)

C++ OOPs Part2

Doubly linked list

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

Memory Efficient LinkedList

Reversal of LinkedList

25 horses 5 tracks Find 3 fastest puzzle

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

1014 Practice Question of New GRE – Princeton

Print Power Set of a Set

Count number of ways to reach a given score in a game

Reverse a Linked List in groups of given size

Coin Collection Dynamic Programming

Possible sizes of bus to carry n groups of friends

Generic Object Oriented Stack with Template

Copyright © 2023 · Genesis Framework · WordPress · Log in