0% found this document useful (0 votes)
28 views14 pages

Python Dictionary and List Operations

The document provides examples of using lists in Python. It demonstrates how to: 1) Create lists and add/insert elements using various methods like append(), insert(), extend(); 2) Access elements using indexes and slicing; 3) Modify lists by changing, removing, popping elements; and 4) Other common list operations like sorting, indexing, slicing etc. It also provides examples of using list comprehensions to generate new lists from existing lists in a concise way.

Uploaded by

ahmed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views14 pages

Python Dictionary and List Operations

The document provides examples of using lists in Python. It demonstrates how to: 1) Create lists and add/insert elements using various methods like append(), insert(), extend(); 2) Access elements using indexes and slicing; 3) Modify lists by changing, removing, popping elements; and 4) Other common list operations like sorting, indexing, slicing etc. It also provides examples of using list comprehensions to generate new lists from existing lists in a concise way.

Uploaded by

ahmed
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link]

pdf

Dictionary
d = dict() # or d = {}

Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})

Dict = dict([(1, 'Geeks'), (2, 'For')])

# Creating a Nested Dictionary

Dict = {1: 'Geeks', 2: 'For', 3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}

# Adding elements one at a time

Dict[0] = 'Geeks'

Dict[2] = 'For'

Dict[3] = 1

# Updating existing Key's Value

Dict[2] = 'Welcome'

# Adding Nested Key value to Dictionary

Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key

print(Dict['name'])

# accessing a element using get()


print([Link](3))

# Deleting a Key value

del Dict[1]

# Nested Dictionary

del Dict['A'][2]

# Deleting a Key

[Link](5)

# Deleting entire Dictionary

[Link]()

# using str() to display dic as string

print (str(dic))

# using str() to display dic as list

print ([Link]())

dict1 = [ 1, 3, 5, 6 ]

# using len() to display dic size

print (len(dic1))

# using type() to display data type

print (type(dic1))

# using copy() to make shallow copy of dictionary

dic3 = {}

dic3 = [Link]()
# printing new dictionary

print ([Link]())

# clearing the dictionary

[Link]()

# Add a key - value pairs to dictionary

d['xyz'] = 123

d['abc'] = 345

{'xyz': 123, 'abc': 345}

# print only the keys or value:

print [Link]() or [Link]()

dic1 = { 'Name' : 'Nandini', 'Age' : 19 }

dic2 = { 'ID' : 2541997 }

# using update to add dic2 values in dic 1

[Link](dic2)

# printing updated dictionary values

print (str(dic1))

{'Age': 19, 'Name': 'Nandini', 'ID': 2541997}

# Initializing sequence

sequ = ('Name', 'Age', 'ID')

# using fromkeys() to transform sequence into dictionary

dict = [Link](sequ,5)
{'Age': 5, 'Name': 5, 'ID': 5}

# using has_key() to check if dic1 has a key

if dict.has_key('Name'):

print ("Name is a key")

else : print ("Name is not a key")

#combining two dictionaries

D1={}

D2={}

[Link](D2)

# using setdefault() to print a key value

print ([Link]('ID', "No ID"))

{'Name': 'Nandini', 'Age': 19, 'ID': 'No ID'}

# for ascending and descending order

import operator

d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

print('Original dictionary : ',d)

sorted_d = sorted([Link](), key=[Link](0)) note: 0 is for key order

sorted_d = sorted([Link](), key=[Link](0),reverse=True) note: 1 is for value order

# for mapping two lists into a dictionaries:

keys = ['red', 'green', 'blue']


values = ['#FF0000','#008000', '#0000FF']

color_dictionary = dict(zip(keys, values))

print(color_dictionary)

#to find maximum and minimum value

my_dict = {'x':500, 'y':5874, 'z': 560}

key_max = max(my_dict.keys(), key=(lambda k: my_dict[k])) NOTE: KEY DEFINE S THE CRITERIA OF FINDING MAX AND MIN

key_min = min(my_dict.keys(), key=(lambda k: my_dict[k])) FOR EXAMPLE IN THIS CASE OUR CRITERIS IS THAT FINDING MAX AND MIN THROUGH

print('Maximum Value: ',my_dict[key_max]) DIC:KEYS

print('Minimum Value: ',my_dict[key_min])

OR
A=list(my_dic.values())

B=list(my_dict.keys())

Print b[[Link](max(A))]

[Link]

:List:
List = []

# Addition of Elements

[Link](1)

[Link](2)

[Link](3)

List after Addition of Three elements:

[1, 2, 4]

# Adding elements to the List

# using Iterator

for i in range(1, 4):

[Link](i)

List after Addition of elements from 1-3:

[1, 2, 4, 1, 2, 3]

# Adding Tuples to the List

[Link]((5, 6))

List after Addition of a Tuple:

[1, 2, 4, 1, 2, 3, (5, 6)]

# Addition of List to a List

List2 = ['For', 'Geeks']

[Link](List2)

List after Addition of a List:


[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]

# Addition of Element at specific position

[Link](3, 12)NOTE: HERE 3 IS INDEX

List after performing Insert Operation:

[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Geeks', 'For', 'Geeks']]

# Addition of multiple elements at the end

[Link]([8, 'Geeks', 'Always'])

List after performing Extend Operation:

[1, 2, 4, 12, 1, 2, 3, (5, 6), ['Geeks', 'For', 'Geeks'], 8, 'Geeks', 'Always']

# accessing a element from the list using index

print(List[0])

print(List[2])

# accessing a element from the nested list

print(List[0][1]) NOTE: IT WILL PRINT WITHOUT SQUARE BRACKETS

print(List[1][0:]) NOTE: IT WILL PRINT WITH SQUARE BRACKETS

# accessing a element using negative index

print(List[-1])

#changing elements of list

List=[1, 2,…..]

List[0:2]=[3, 4] NOTE: HERE 2 IS NOT INCLUDE THESE ARE THE INDEX.

Now output is
List=[3, 4,…}

#adding element to list

List=[1, 2, 3, 4]

Print(list + [5, 21 ])

List=[1, 2, 3, 4, 5, 21]

# Removing elements from List

[Link](5) note: 5 is not the index. It is the element.

# Removing elements from List using iterator method

for i in range(1, 5): note:(1, 5) are not index

[Link](i)

# removing item from list

Del list[index] NOTE: ITEM AT GIVEN INDEX WILL BE DELETED

# Removing last element

[Link]()

# Removing element with index

[Link](2) note:2 is index

# Creating a List

List = ['G','E','E','K','S','F', 'O','R','G','E','E','K','S']

# using Slice operation

Sliced_List = List[3:8] NOTE: 3 AND 8 IS INDEX

['K', 'S', 'F', 'O', 'R']


# Print elements from beginning to a pre-defined point using Slice

Sliced_List = List[:-6]

['G', 'E', 'E', 'K', 'S', 'F', 'O']

Sliced_List = List[5:]

['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

# Printing elements from beginning till end

Sliced_List = List[:]

# Printing elements in reverse

Sliced_List = List[::-1]

# Will print the index of '4' in list1

print([Link](4))

# Will print the index of 'cat' in list2

print([Link]('cat'))

# Random list having sublist and tuple also

list1 = [1, 2, 3, [9, 8, 7], ('cat', 'bat')]

# Will print the index of sublist [9, 8, 7]

print([Link]([9, 8, 7]))

# adding items of list

list=[1, 2, 3, 4, 5]

print(list[1] + list[2])

output is (BC)
#TIPS

x=[1, 2, 3, 4] x=[1 , 2, 3, 4]

y=x y=list(x)

y[1]=4 INSTEAD THIS y=[:]

then, y=[1, 4, 3, 4] y[1]=4

and x=[1, 4, 3, 4] x=[1, 2, 3, 4]

[Link](arr, substring, start=0, end=None): Finds the lowest index of the sub-
string in the specified range But if substring is not found, it raises ValueError.
import numpy as np

arr = ['this is geeks for geek']

print ("arr : ", arr)

print ("\nindex of 'geeks' : ", [Link](arr, 'geeks'))

arr : ['this is geeks for geek']

index of 'geeks' : [8]

import numpy as np

arr = ['this is geeks for geek']

print ("\nindex of 'geeks' : ", [Link](arr, 'geeks', start = 2))

print ("\nindex of 'geeks' : ", [Link](arr, 'geeks', start = 10))


print ("\nindex of 'geek' : ", [Link](arr, 'geek', start = 10))

index of 'geeks' : [8]

ValueError: substring not found

index of 'geek' : [18]

list comprehension:
1=[expression for variable in range]
List=[] a/c to comprehension square=[i**2 for x in
For x in range(1, 101): print(square)
[Link](x**2)
Print(square)
2=[expression for variable in range if <cond>]

List=[movies name] a/c to comprehension movies=[tittle For tittle in list If [Link](“G”)]


List2=[]
For tittle in list:
If [Link](“G”)
[Link](tittle)
3=[expression for variable in range if <cond1> and <cond2>]
List=[(movie, year),…] a/c to comprehension movies=[tittle for key, value in list if value > 200 and

For key, value in list: [Link](“G”)]

If value>2000

Print(tittle)
4=[expression for variable-1 in range-1 and variable-2 in range-2]
Cartesion product:

A=[1, 2, 3, 4, 5]

B=[1, 2, 3, 4, 5]

List=[(a, b) for a in A for b in B]

Print(list)

print(" LIST COMPREHENSION")


lism=[1, 2, 3, 4, 5]
print("original list",lism)
print(" method # 01")
a=[]
for x in lism:
[Link](x*x)
print(a)
print(" now method # 02")
b=[x*x for x in lism]
print(b)
print(" then method # 03")
c=list(map(lambda x: x*x, lism))
print(c)
print(" method # 04")
d=list(map(square, lism))
print(d)

a=input("enter temperature ")

no=a[:-1]

if a[-1]=="F":

c = int((0.5555) * (no- 32))

print(c,"C")

elif a[-1]=="C":

c=int((1.8)*(1/no -32))

print(c,"F")

else:

print("incorrect input")

You might also like