Saturday, January 31, 2026
HomeLanguagesFormatting containers using format() in Python

Formatting containers using format() in Python

Let us see how to format containers that were accessed through  __getitem__ or getattr() using the format() method in Python.

Accessing containers that support __getitem__

a) For Dictionaries

Python3




# creating a dictionary
founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'}
 
# formatting
print('{f[Microsoft]} {f[Apple]}'.format(f = founder))


Output :

Bill Gates Steve Jobs

f[Microsoft] is replaced by Bill Gates and f[Apple] is replaced by Steve Jobs.

b) For lists

Python3




# creating a list
list_items = [1, 3, 5, 7, 9, 11]
 
# formatting
print('{l[3]} {l[5]}'.format(l = list_items))


Output :

7 11

Accessing attributes on objects that support getattr()

a) For Class

Python3




# creating a class
class Program(object):
    language = 'Python'
 
# formatting
print('{p.language}'.format(p = Program()))


Output :

Python

p.language is replaced by Python as language is an attribute of Program

Accessing the nested structure

Python3




# creating a class
class Program(object):
    language = 'Python'
     
    # creating a dictionary
    versions = [{'version': '1'}, {'version': '2'}, {'version': '3'}]
 
# formatting
print('{p.language}: {p.versions[2][version]}'.format(p = Program()))


Output :

Python: 3
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
123 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS