0% found this document useful (0 votes)
2 views1 page

Python Dictionary Methods

The document outlines various methods available for Python dictionaries, including keys(), values(), items(), get(), update(), pop(), popitem(), clear(), copy(), setdefault(), and fromkeys(). Each method is briefly described with its functionality. An example dictionary is provided to illustrate the usage of these methods.

Uploaded by

abhayshukla6263
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)
2 views1 page

Python Dictionary Methods

The document outlines various methods available for Python dictionaries, including keys(), values(), items(), get(), update(), pop(), popitem(), clear(), copy(), setdefault(), and fromkeys(). Each method is briefly described with its functionality. An example dictionary is provided to illustrate the usage of these methods.

Uploaded by

abhayshukla6263
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

Python Dictionary Methods

keys() → Returns all keys in the dictionary.

values() → Returns all values in the dictionary.

items() → Returns key-value pairs as tuples.

get(key, default) → Returns the value of the key; returns default if key not found.

update(other_dict) → Updates dictionary with another dictionary (or key-value pairs).

pop(key, default) → Removes the specified key and returns its value.

popitem() → Removes and returns the last inserted key-value pair.

clear() → Removes all items from the dictionary.

copy() → Returns a shallow copy of the dictionary.

setdefault(key, default) → Returns value of the key; if key doesn’t exist, inserts it with default.

fromkeys(keys, value) → Creates a new dictionary from given keys with the same value.

Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict.keys()) # dict_keys(['a', 'b', 'c'])
print(my_dict.values()) # dict_values([1, 2, 3])
print(my_dict.items()) # dict_items([('a', 1), ('b', 2), ('c', 3)])
print(my_dict.get('b')) # 2
my_dict.update({'d': 4})
print(my_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

You might also like