top of page

Dictionary methods 

 .keys(); .values(); .items(); .get(); .setdefault(); .sorted(); .set()

Note: the values returned by there methods .keys(), .values(), and .items() are NOT true lists: they can NOT be modified and do not have an append() method. BUT there data types (dict_keys, dict_values, and dict_items) can be used in FOR loops

.keys()

input: dict

output: NOT true list, but can be used in for loops

E.g.1

>>> spam = {'color': 'red', 'age': 42}

>>> for k in spam.keys(): 

...     print(k)

... 

color

age

.values()

input: dict

output: NOT true list, but can be used in for loops

E.g.1

>>> spam = {'color': 'red', 'age': 42}

>>> for v in spam.values(): 

...     print(v)

... 

red

42

.items()

input: dict

output: NOT true tuple, but can be used in for loops

E.g.1.note the return value is tuple

>>> spam = {'color': 'red', 'age': 42}

>>> for i in spam.items(): 

...     print(i)

... 

('color', 'red')

('age', 42)

.get() - doesn't change dict's value v.s .setdefault()

input: dict

output: int

E.g.1

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

>>> 'I am bringing ' + str(picnicItems.get('cups', 0)) + ' cups.'

'I am bringing 2 cups.'

>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'

'I am bringing 0 eggs.'

>>> 

.setdefault() - changes dict's value v.s .get()

input: dict

output: int

E.g.1.

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

 

>>> 'I am bringing ' + str(picnicItems.get('eggs', 0)) + ' eggs.'

'I am bringing 0 eggs.'

>>> picnicItems

{'apples': 5, 'cups': 2}

 

>>> 'I am bringing ' + str(picnicItems.setdefault('eggs', 0)) + ' eggs.'

'I am bringing 0 eggs.'

>>> picnicItems

{'eggs': 0, 'apples': 5, 'cups': 2}

.sorted() - changes dict's value v.s .get()

input: dict

output: dict

E.g.1

favorite_languages = {

'jen': 'python',

'sarah': 'c',

'edward': 'ruby',

'phil': 'python'

}

 

>>> for name in sorted(favorite_languages.keys()):
...     print(name.title() + ', thank you for taking the poll.')
...
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
>>>

.set() - filter out duplicates 

input: dict

output: dict

E.g.1

>>> favorite_languages = {
... 'jen': 'python',
... 'sarah': 'c',
... 'edward': 'ruby',
... 'phil': 'python'
... }
>>> print('The following languages have been mentioned: ')
The following languages have been mentioned:
>>> for language in set(favorite_languages.values()):
...     print(language.title())
...
Python
C
Ruby
>>>

NOTICE: python only outputs once 

bottom of page