Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
119 views

We Can Create Dictionary With Following Four Methods

The document discusses various methods to create, add elements to, access elements from, modify, and delete elements from dictionaries in Python. It describes creating dictionaries with different key types like integers, strings, and mixed keys. Methods covered include creating empty dictionaries, adding elements one at a time or as sets, updating and accessing elements, deleting elements using del, pop(), popitem(), and clear(). It also provides a table summarizing common dictionary methods like copy(), clear(), pop(), get(), values(), update(), setdefault(), keys(), items(), and more.

Uploaded by

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

We Can Create Dictionary With Following Four Methods

The document discusses various methods to create, add elements to, access elements from, modify, and delete elements from dictionaries in Python. It describes creating dictionaries with different key types like integers, strings, and mixed keys. Methods covered include creating empty dictionaries, adding elements one at a time or as sets, updating and accessing elements, deleting elements using del, pop(), popitem(), and clear(). It also provides a table summarizing common dictionary methods like copy(), clear(), pop(), get(), values(), update(), setdefault(), keys(), items(), and more.

Uploaded by

Ghanshyam Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

We can create dictionary with following four methods

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Delhi', 2: 'Ajmer', 3: 'Beawar'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'INFOTECH', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'yellow', 2: 'white', 3:'green'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Amit'), (2, 'Sumit')])
print("\nDictionary with each item as a pair: ")
print(Dict)

# Creating a Nested Dictionary


# as shown in the below image
Dict = {1: 'Anita', 2: 'Sunita',
3:{'First Name' : 'Vinita', 'Middle Name' : 'Sumit', 'Last Name' :
'Surana'}}
print(Dict)

Adding Elements to Dictionary


# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = ‘INFOTECH’
Dict[2] = ‘COMPUTER’
Dict[3] = ‘EDUCATION’
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

# Adding Nested Key value to Dictionary


Dict[5] = {'Nested' :{'1' : 'Ajmer', '2' : 'Jaipur'}}
print("\nAdding a Nested Key: ")
print(Dict)

Accessing Elements from the Dictionary


# Python program to demonstrate
# accesing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Computer', 'name': 'INFOTECH', 3: 'Education'}

# accessing a element using key


print("Acessing a element using key:")
print(Dict['name'])

# accessing a element using key


print("Acessing a element using key:")
print(Dict[1])

# accessing a element using get()


# method
print("Acessing a element using get:")
print(Dict.get(3))

Removing Elements from Dictionary


# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'INFOTECH',
'A' : {1 : 'Ajmer', 2 : 'Road', 3 : 'Kishangarh'},
'B' : {1 : 'Rajasthan', 2 : 'India'}}
print("Initial Dictionary: ")
print(Dict)

# Deleting a Key value


del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)

# Deleting a Key
# using pop()
Dict.pop(5)
print("\nPopping specific element: ")
print(Dict)

# Deleting a Key
# using popitem()
Dict.popitem()
print("\nPops first element: ")
print(Dict)

# Deleting entire Dictionary


Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)

Dictionary Methods

METHODS DESCRIPTION

copy() They copy() method returns a shallow copy of the dictionary.

clear() The clear() method removes all items from the dictionary.

pop() Removes and returns an element from a dictionary having the given key.

popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.

get() It is a conventional method to access a value for a key.

dictionary_name.values() returns a list of all the values available in a given dictionary.

str() Produces a printable string representation of a dictionary.

update() Adds dictionary dict2’s key-values pairs to dict

setdefault() Set dict[key]=default if key is not already in dict

keys() Returns list of dictionary dict’s keys


items() Returns a list of dict’s (key, value) tuple pairs

has_key() Returns true if key in dictionary dict, false otherwise

fromkeys() Create a new dictionary with keys from seq and values set to value.

type() Returns the type of the passed variable.

cmp() Compares elements of both dict.

Q1. WAP to create a phone directory and print phone numbers of all the friends?

An.s.

Pd={“ram”:9829089288,”shyam”:9938934844,”Mohan”:93849899,”Sohan”:93489349}

for name in pd:

print (name,”:”,pd[name])

NOTE : we can print all the keys with pd.keys();

NOTE : we can print all the values with pd.values();

You might also like