DEV Community

Cover image for Python: Part 2 - Dictionaries with demos
Srinivasulu Paranduru for AWS Community Builders

Posted on • Edited on

Python: Part 2 - Dictionaries with demos

Dictionaries in Python:

1. Dictionaries

Try the commands in IDLE Shell
myCat = {'size':'fat','color':'gray','disposition':'loud'}
myCat['size']
#Output : fat
Enter fullscreen mode Exit fullscreen mode

'My cat has ' + myCat['color'] + ' fur.'

output : 'My cat has gray fur.'

Comparing the lists
[1,2,3] == [3,2,1]
#False
Enter fullscreen mode Exit fullscreen mode
Comparing the dictionaries with same key value pairs in different order
info = {'size':'fat','color':'gray','disposition':'loud'}
info1 = {'color':'gray','disposition':'loud','size':'fat'}
info == info1
>Output:  True
Enter fullscreen mode Exit fullscreen mode
check the keys existing in a dictionary
'color' in info
#True
'color' not in info
#False
Enter fullscreen mode Exit fullscreen mode

1.1 Dictionary methods - keys(),values() and items()

1.1.1 Try the command:
list(info.keys())
Enter fullscreen mode Exit fullscreen mode

Output:
['size', 'color', 'disposition']

1.1.2 Try the command:
info.values()
Enter fullscreen mode Exit fullscreen mode

Output:
dict_values(['fat', 'gray', 'loud'])

1.1.3 Try the command:
 list(info.values())
Enter fullscreen mode Exit fullscreen mode

Output
['fat', 'gray', 'loud']

1.1.4 Try the command:
info.items()
Enter fullscreen mode Exit fullscreen mode

Output:
dict_items([('size', 'fat'), ('color', 'gray'), ('disposition', 'loud')])

1.1.5 Try the command:
list(info.items())
Enter fullscreen mode Exit fullscreen mode

Output:
[('size', 'fat'), ('color', 'gray'), ('disposition', 'loud')]

Dictionary with for loop

1.1.6 Try the command -
for k in info.keys() :
  print(k)
Enter fullscreen mode Exit fullscreen mode

output:

size
color
disposition

1.1.7 Try the command -
for v in info.values() :
   print(v)
Enter fullscreen mode Exit fullscreen mode

output:

fat
gray
loud

1.1.8 Try the command -
for k,v in info.items():
    print(k,v)
Enter fullscreen mode Exit fullscreen mode

output:
size fat
color gray
disposition loud

1.1.9 Try the command -
for i in info.items():
   print(i)
Enter fullscreen mode Exit fullscreen mode

output:
('size', 'fat')
('color', 'gray')
('disposition', 'loud')

1.1.10 Try the command -
'fat' in info.values()
Enter fullscreen mode Exit fullscreen mode

output: True

1.2 The get() Dictionary Method

Pre-requisties : Set the variable info with the dictionary value

info = {'size':'fat','color':'gray','disposition':'loud'}
Enter fullscreen mode Exit fullscreen mode
1.2.1
 if 'color' in info:
      print(info['color'])

 #output:  gray

Enter fullscreen mode Exit fullscreen mode
1.2.2
if 'dress' in info :
      print(info['dress'])
#output:  ''
Enter fullscreen mode Exit fullscreen mode
1.2.3 : If the key - size exists it returns its value else empty string will be returned
info.get('size','')

Enter fullscreen mode Exit fullscreen mode

output : 'fat'

1.2.4: If the key - size it returns its value else empty string will be returned
info.get('size','medium')

Enter fullscreen mode Exit fullscreen mode

output : ''

1.2.5
picnicItems = {'apples':5,'cups':2}

print('I am bringing ' + str(picnicItems.get('napkins',0)) +' to the picnic.')
Enter fullscreen mode Exit fullscreen mode

output: I am bringing 0 to the picnic.

1.2.6
picnicItems = {'apples':5,'cups':2}

print('I am bringing ' + str(picnicItems['napkins']) +' to the picnic.')
Enter fullscreen mode Exit fullscreen mode

output: Error message
Traceback (most recent call last):
File "", line 1, in
print('I am bringing ' + str(picnicItems['napkins']) +' to the picnic.')
KeyError: 'napkins'

1.2.7 : setdefault()
eggs = {'name':'Zophie','species':'cat','age':8}
eggs.setdefault('color','black')
#output: 'black'
eggs
#output: {'name': 'Zophie', 'species': 'cat', 'age': 8, 'color': 'black'}

#if the default existing for the color key then the value won't be changed.
eggs.setdefault('color','orange')
#output: 'black'
eggs
{'name': 'Zophie', 'species': 'cat', 'age': 8, 'color': 'black'}

Enter fullscreen mode Exit fullscreen mode
1.2.8: character count program
1.2.8.1
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)

Enter fullscreen mode Exit fullscreen mode

output:
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'q': 1, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}

1.2.8.2 : convert the message to upper case and print the count
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message.upper() :
    count.setdefault(character,0)
    count[character]=count[character]+1

print(count)

Enter fullscreen mode Exit fullscreen mode

output:
{'I': 7, 'T': 6, ' ': 13, 'W': 2, 'A': 5, 'S': 3, 'B': 1, 'R': 5, 'G': 2, 'H': 3, 'C': 3, 'O': 2, 'L': 3, 'D': 3, 'Q': 1, 'Y': 1, 'N': 4, 'P': 1, ',': 1, 'E': 5, 'K': 2, '.': 1}

1.2.8.3 : comment the line count.setdefault(character,0) and check the response.
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message.upper() :
    # count.setdefault(character,0) 
    count[character]=count[character]+1

print(count)

Enter fullscreen mode Exit fullscreen mode

output:
Traceback (most recent call last):
File "C:/Srinivas/3 Code/PythonPrograms/charactercount.py", line 6, in
count[character]=count[character]+1
KeyError: 'I'


count.setdefault(character,0)
This line will set the count of the character to 0 for the first time, if the variable does not exists.

1.2.8.4: Big message is assigned to the variable message and its using ''' at the start and end of the message.
message = '''Ensure your post has a cover image set to make the most of the home feed and social media platforms.
Share your post on social media platforms or with your co-workers or local communities.
Ask people to leave questions for you in the comments. It's a great way to spark additional discussion describing personally why you wrote it or why people might find it helpful.'''

count = {}

for character in message.upper() :
    count.setdefault(character,0)
    count[character]=count[character]+1

print(count)

Enter fullscreen mode Exit fullscreen mode

output:
{'E': 30, 'N': 12, 'S': 24, 'U': 10, 'R': 19, ' ': 62, 'Y': 9, 'O': 35, 'P': 11, 'T': 23, 'H': 11, 'A': 22, 'C': 9, 'V': 2, 'I': 21, 'M': 13, 'G': 4, 'K': 4, 'F': 7, 'D': 9, 'L': 14, '.': 4, '\n': 2, 'W': 6, '-': 1, 'Q': 1, "'": 1, 'B': 1}

1.2.8.5 : Import pprint module
import pprint
message = '''Ensure your post has a cover image set to make the most of the home feed and social media platforms.
Share your post on social media platforms or with your co-workers or local communities.
Ask people to leave questions for you in the comments. It's a great way to spark additional discussion describing personally why you wrote it or why people might find it helpful.'''

count = {}

for character in message.upper() :
    count.setdefault(character,0)
    count[character]=count[character]+1

pprint.pprint(count)

Enter fullscreen mode Exit fullscreen mode

output:
==============================
{'\n': 2,
' ': 62,
"'": 1,
'-': 1,
'.': 4,
'A': 22,
'B': 1,
'C': 9,
'D': 9,
'E': 30,
'F': 7,
'G': 4,
'H': 11,
'I': 21,
'K': 4,
'L': 14,
'M': 13,
'N': 12,
'O': 35,
'P': 11,
'Q': 1,
'R': 19,
'S': 24,
'T': 23,
'U': 10,
'V': 2,
'W': 6,
'Y': 9}

1.2.8.5 : using pprint module and using pformat
import pprint
message = '''Ensure your post has a cover image set to make the most of the home feed and social media platforms.
Share your post on social media platforms or with your co-workers or local communities.
Ask people to leave questions for you in the comments. It's a great way to spark additional discussion describing personally why you wrote it or why people might find it helpful.'''

count = {}

for character in message.upper() :
    count.setdefault(character,0)
    count[character]=count[character]+1

stext=pprint.pformat(count)
print(stext)

Enter fullscreen mode Exit fullscreen mode

output:
{'\n': 2,
' ': 62,
"'": 1,
'-': 1,
'.': 4,
'A': 22,
'B': 1,
'C': 9,
'D': 9,
'E': 30,
'F': 7,
'G': 4,
'H': 11,
'I': 21,
'K': 4,
'L': 14,
'M': 13,
'N': 12,
'O': 35,
'P': 11,
'Q': 1,
'R': 19,
'S': 24,
'T': 23,
'U': 10,
'V': 2,
'W': 6,
'Y': 9}

1.2.9 : List of dictionaries
>>> allCats=[]
>>> allCats.append({'name':'Zophie','age':7,'color':'gray'})
>>> allCats.append({'name':'Pooka','age':5,'color':'gray'})
>>> allCats.append({'name':'Fat-tail','age':4,'color':'red'})
>>> allCats
[{'name': 'Zophie', 'age': 7, 'color': 'gray'}, {'name': 'Pooka', 'age': 5, 'color': 'gray'}, {'name': 'Fat-tail', 'age': 4, 'color': 'red'}]
Enter fullscreen mode Exit fullscreen mode

Recap :

  • Dictionaries contain key-value pairs. Keys are like a list's indexes.
  • Dictionaries are mutable. Variables hold references to dictionary values, not the dictionary value itself.
  • Dictionaries are unordered. There is no "first" key-value pair in a dictionary.
  • The keys(), values(), and items() methods will return list-like values of a dictionary's keys, vaues, and both keys and values, respectively.
  • The get() method can return a default value if a key doesn't exist.
  • The setdefault() method can set a value if a key doesn't exist.
  • The pprint module's pprint() "pretty print" function can display a dictionary value cleanly. The pformat() function returns a string value of this output.

Conclusion : Discussed about python - dictionaries used IDLE shell command for running the python code

💬 If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it 😀 and share this blog with ur friends and follow me in linkedin

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Best Practices for Running  Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK cover image

Best Practices for Running Container WordPress on AWS (ECS, EFS, RDS, ELB) using CDK

This post discusses the process of migrating a growing WordPress eShop business to AWS using AWS CDK for an easily scalable, high availability architecture. The detailed structure encompasses several pillars: Compute, Storage, Database, Cache, CDN, DNS, Security, and Backup.

Read full post