0% found this document useful (0 votes)
6 views16 pages

Module 3 4 PLC

The document contains Python code snippets demonstrating various operations with dictionaries and file handling using the os module. It covers changing directories, listing files, manipulating dictionary items, and using methods like update, pop, and setdefault. Additionally, it includes examples of counting characters in a string and comparing dictionaries with lists.

Uploaded by

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

Module 3 4 PLC

The document contains Python code snippets demonstrating various operations with dictionaries and file handling using the os module. It covers changing directories, listing files, manipulating dictionary items, and using methods like update, pop, and setdefault. Additionally, it includes examples of counting characters in a string and comparing dictionaries with lists.

Uploaded by

Prajval (Arun)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

import os

print(os.getcwd())
os.chdir("D:\\")
print(os.getcwd())

# # os.makedirs("./Arun")
# print(os.listdir("."))

os.chdir("./Arun")
print(os.getcwd())

# os.makedirs("./A.txt")
print(os.listdir("."))
D:\Arun
D:\
D:\Arun
['a.txt']
a = {1:2, 2:4}
b = a.items()
print(b)
c = a.keys()
print(c)
d = a.values()
print(d)

a.update({2:34})
print(a)
dict_items([(1, 2), (2, 4)])
dict_keys([1, 2])
dict_values([2, 4])
{1: 2, 2: 34}
import os
print(os.getcwd())

print(os.path.abspath("arun"))

print(os.path.isabs("."))
D:\Arun
D:\Arun\arun
False
import os

print(os.getcwd())

print(os.path.relpath("C:\\User\\56", "C:\\User"))
D:\Arun
56
import os
print(os.getcwd())

print(os.path.getsize("./a.txt"))
D:\Arun
0
import os
import pprint

print(os.getcwd())

pprint.pprint(os.listdir("."))
D:\
['$RECYCLE.BIN',
'advanced-note-uploader',
'Arun',
'C',
'colleges_cutoff.xlsx',
'Dra 1.d ',
'IITG resumes',
'Photoshop Temp154531856',
'Photoshop Temp242832832',
'Photoshop Temp27818645420',
'Photoshop Temp3419565896',
'Photoshop Temp8206072564',
'PSAutoRecover',
'System Volume Informa on']
import os

print(os.path.basename("D:\\Arun\\a.txt"))

print(os.path.dirname("D:\\Arun\\a.txt"))
a.txt
D:\Arun
import os

print(("D:\\Arun\\a.txt").split(os.path.sep))
print(os.path.exists("D:\\Arun\\a.txt"))

print(os.path.isdir("D:\\Arun"))
['D:', 'Arun', 'a.txt']
True
True
import os

print(os.getcwd())

a = open("./a.txt", "a")
b = a.write(" shdhsdshds dhsdhshArun Kumar S B")
a.close()
D:\Arun
ep1={111: 23, 112:33, 113:54}
ep2={115: 87, 119:73, 118:98}

for v in ep1.items():
print(v)
# (111, 23)
# (112, 33)
# (113, 54)
for v in ep1.keys():
print(v)
# 111
# 112
# 113

for v in ep1.values():
print(v)
# 23
# 33
# 54

ep1={111: 23, 112:33, 113:54}


ep2={115: 87, 119:73, 118:98}
ep1.update(ep2)
print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# {111: 23, 112: 33, 113: 54, 115: 87, 119: 73, 118: 98}

ep1={111: 23, 112:33, 113:54}


ep1.clear()
print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# {}

ep1={111: 23, 112:33, 113:54}


ep1.pop(111)
print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# {112: 33, 113: 54}

ep1={111: 23, 112:33, 113:54}


ep1.popitem() #removes last item
print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# {111: 23, 112: 33}

ep1={111: 23, 112:33, 113:54}


del ep1[111] #removes any key value pair
print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# {112: 33, 113: 54}
ep1={111: 23, 112:33, 113:54}
del ep1 #delete full dic onary
# print(ep1)
# [Running] python -u "c:\Users\56\3D Objects\A\a.py"
# Traceback (most recent call last):
# File "c:\Users\56\3D Objects\A\a.py", line 26, in <module>
# print(ep1)
# ^^^
# NameError: name 'ep1' is not defined. Did you mean: 'ep2'?

print()

# in and no n operator
ep1={111: 23, 112:33, 113:54}
a = 232 in ep1.keys()
print(a)
# False

b = 232 not in ep1.items()


print(b)
# True
print()

# get(key, fallback)
ep1={111: 23, 112:33, 113:54}
a = ep1.get(1123)
print(a)
# None

print()

# SLicing the dic onary


import itertools
# itertools.islice(iterable, start, stop)
ep1={111: 23, 112:33, 113:54}
a = dict(itertools.islice(ep1.items(), 2))
print(a)
# {111: 23, 112: 33}

print()

# set default
ep1={111: 23, 112:33, 113:54}
ep1.setdefault(0)
print(ep1)
# {111: 23, 112: 33, 113: 54, 0: None}

print()

ep1={111: 23, 112:33, 113:54, 0:"owner"}


ep1.setdefault(0)
print(ep1)
# {111: 23, 112: 33, 113: 54, 0: 'owner'}

print()

ep1={111: 23, 112:33, 113:54}


ep1.setdefault(0, "OWNER")
print(ep1)
"""{111: 23, 112: 33, 113: 54, 0: 'OWNER'}"""

print()

ep1={111: 23, 112:33, 113:54, 0:"Owner"}


print(ep1)
ep1.setdefault(0, "Myself")
print(ep1)
# {111: 23, 112: 33, 113: 54, 0: 'Owner'}
# {111: 23, 112: 33, 113: 54, 0: 'Owner'}

print()

# Important ques on
message = 'It was a bright cold day in April, and the clocks
were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)

# pre y print
import pprint
message = 'It was a bright cold day in April, and the clocks
were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
pprint.pprint(count)

# 1. What does the code for an empty dic onary look like?
# An empty dic onary is defined using curly braces {}:

# python
# Copy code
# empty_dict = {}
# 2. What does a dic onary value with a key 'foo' and a value
42 look like?
# A dic onary with the key 'foo' and value 42 looks like:

# python
# Copy code
# {'foo': 42}
# 3. What is the main difference between a dic onary and a
list?
# Dic onary:

# A dic onary is an unordered collec on of key-value pairs.


# Keys are unique and used to access values.
# Example: {'foo': 42, 'bar': 100}
# List:

# A list is an ordered collec on of items.


# Items are accessed by their index.
# Example: [42, 100, 'foo']
# 4. What happens if you try to access spam['foo'] if spam is
{'bar': 100}?
# If you try to access spam['foo'] when spam = {'bar': 100},
Python raises a KeyError because the key 'foo' does not exist in
the dic onary.

# 5. If a dic onary is stored in spam, what is the difference


between the expressions 'cat' in spam and 'cat' in spam.keys()?
# 'cat' in spam:

# Checks if the key 'cat' exists in the dic onary spam.


# Equivalent to 'cat' in spam.keys().
# 'cat' in spam.keys():

# Explicitly checks if 'cat' is in the dic onary's keys.


# Func onally the same as 'cat' in spam.
# Both expressions return True if 'cat' is a key in the dic onary
and False otherwise.

# 6. If a dic onary is stored in spam, what is the difference


between the expressions 'cat' in spam and 'cat' in
spam.values()?
# 'cat' in spam:

# Checks if 'cat' is a key in the dic onary spam.


# 'cat' in spam.values():

# Checks if 'cat' is a value in the dic onary spam.


# These expressions are not equivalent. The first checks keys,
while the second checks values.

# 7. What is a shortcut for the following code?


# python
# Copy code
# if 'color' not in spam:
# spam['color'] = 'black'
# The shortcut is to use the setdefault() method:

# python
# Copy code
# spam.setdefault('color', 'black')
# setdefault() checks if the key 'color' exists:
# If it does, it returns the exis ng value.
# If it doesn't, it sets 'color' to 'black'.
# 8. What module and func on can be used to "pre y print"
dic onary values?
# The pprint module and its pprint() func on can be used to
"pre y print" dic onary values:

# python
# Copy code
# from pprint import pprint

# my_dict = {'foo': 42, 'bar': 100, 'baz': [1, 2, 3]}


# pprint(my_dict)

You might also like