0% found this document useful (0 votes)
128 views

Advantages of Dictionary

The document discusses dictionaries in Python. Some key points: - Dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. - Common dictionary methods allow adding, removing, accessing, and iterating over key-value pairs. - Built-in functions like len(), keys(), items(), get(), pop(), update() manipulate dictionaries. - Dictionaries can be sorted, iterated over, counted, and created using comprehension syntax.

Uploaded by

Jyotirmay Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views

Advantages of Dictionary

The document discusses dictionaries in Python. Some key points: - Dictionaries are unordered collections of key-value pairs where keys must be unique and immutable. - Common dictionary methods allow adding, removing, accessing, and iterating over key-value pairs. - Built-in functions like len(), keys(), items(), get(), pop(), update() manipulate dictionaries. - Dictionaries can be sorted, iterated over, counted, and created using comprehension syntax.

Uploaded by

Jyotirmay Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

7.

Dictionary

Python dictionary is an unordered collection of items. While other compound data types
have only value as an element, a dictionary has a key: value pair.

Advantages of Dictionary
 Dictionaries are optimized to retrieve values when the key is known.
 Dictionaries in a programming language is a type of data-structure used to store
information connected in someway.

7.1. Property of a Dictionary


 Keys will be a single element
 Values can be a list or list within a list, numbers, etc.
 More than one entry per key is not allowed ( no duplicate key is allowed)
 The values in the dictionary can be of any type while the keys must be immutable
like numbers, tuples or strings.
 Dictionary keys are case sensitive- Same key name but with the different case are
treated as different keys in Python dictionaries.

7.2. Creating a Tuple

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
7.3. Accessing values in Dictionary
Ex:

my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']

Result:
Jack
26

7.4. Add element to Dictionary

Ex:
my_dict = {'name':'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

Result:
{'age': 27, 'name': 'Jack'}
{'age': 27, 'name': 'Jack', 'address': 'Downtown'}
7.5. Remove element to Dictionary

# create a dictionary

squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item

# Output: 16

print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}

print(squares)

# remove an arbitrary item

# Output: (1, 1)

print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}

print(squares)

# delete a particular item

del squares[5]

# Output: {2: 4, 3: 9}

print(squares)

# remove all items

squares.clear()

# Output: {}

print(squares)

# delete the dictionary itself

del squares

# Throws Error

# print(squares)
7.6. Built-in Dictionary Functions & Methods
len() Method:

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}


print("Length : %d" % len (Dict))

Variable Type:

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}


print("variable Type: %s" %type (Dict))

 Use the code %type to know the variable type


 When code was executed, it tells a variable type is a dictionary

cmp() Method:

cmp is not supported in Python 3

Str(dict):

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}


print("printable string:%s" % str (Dict))

 It will return the dictionary elements into a printable string format

Check length:

released = {
"iphone" : 2007,
"iphone 3G" : 2008,
"iphone 3GS" : 2009,
"iphone 4" : 2010,
"iphone 4S" : 2011,
"iphone 5" : 2012
}
print len(released)
Test the Dictionary:

>>> my_dict = {'a' : 'one', 'b' : 'two'}


>>> 'a' in my_dict
True
>>> 'b' in my_dict
True
>>> 'c' in my_dict
False

or

for item in released:


if "iphone 5" in released:
print "Key found"
break
else:
print "No keys found"

Result:

Key Found

Print All Key & Values:

for key,val in released.items():


print key, "=>", val
>>output
iphone 3G => 2008
iphone 4S => 2011
iphone 3GS => 2009
iphone => 2007
iphone 5 => 2012
iphone 4 => 2010

Only Keys:

phones = released.keys()
print phones

Printing with "pprint":

pprint.pprint(released)

Sorting the Dictionary:

for key, value in sorted(released.items()):


print key, value

>>output:
('iphone', 2007)
('iphone 3G', 2008)
('iphone 3GS', 2009)
('iphone 4', 2010)
('iphone 4S', 2011)
('iphone 5', 2012)
"""

or

for phones in sorted(released, key=len):


print phones, released[phones]

>>output:
iphone 2007
iphone 5 2012
iphone 4 2010
iphone 3G 2008
iphone 4S 2011
iphone 3GS 2009

Counting:

count = {}
for element in released:
count[element] = count.get(element, 0) + 1
print count

>>output:
{'iphone 3G': 1, 'iphone 4S': 1, 'iphone 3GS': 1, 'iphone': 1,
'iphone 5': 1, 'iphone 4': 1}

7.7 Summary:

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v (defaults to None).
Return the value of key. If key doesnot exit, return d(defaults
get(key[,d])
to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is not found.
pop(key[,d])
If d is not provided and key is not found, raises KeyError.

Remove and return an arbitary item (key, value). Raises KeyError if the
popitem()
dictionary is empty.

If key is in the dictionary, return its value. If not, insert key with a value
setdefault(key[,d])
of d and return d (defaults to None).

Update the dictionary with the key/value pairs from other, overwriting
update([other])
existing keys.

values() Return a new view of the dictionary's values

7.8 Dictionary Comprehension

squares = {x: x*x for x in range(6)}


# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)

Result:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

You might also like