Python Dictionary Methods

Python Dictionary Methods

Python dictionaries offer a variety of methods that allow you to manipulate and work with them effectively. Here's an overview of some of the most commonly used dictionary methods:

  1. clear(): Removes all items from the dictionary.

    d = {'a': 1, 'b': 2} d.clear() print(d) # Output: {} 
  2. copy(): Returns a shallow copy of the dictionary.

    d = {'a': 1, 'b': 2} d_copy = d.copy() print(d_copy) # Output: {'a': 1, 'b': 2} 
  3. fromkeys(seq, value=None): Creates a new dictionary with keys from seq and values set to value.

    keys = ['a', 'b', 'c'] d = dict.fromkeys(keys, 0) print(d) # Output: {'a': 0, 'b': 0, 'c': 0} 
  4. get(key, default=None): Returns the value for a key if it exists in the dictionary, otherwise returns default.

    d = {'a': 1, 'b': 2} print(d.get('a', 0)) # Output: 1 print(d.get('c', 0)) # Output: 0 
  5. items(): Returns a view object that displays a list of dictionary's (key, value) tuple pairs.

    d = {'a': 1, 'b': 2} print(list(d.items())) # Output: [('a', 1), ('b', 2)] 
  6. keys(): Returns a view object that displays a list of all the keys.

    d = {'a': 1, 'b': 2} print(list(d.keys())) # Output: ['a', 'b'] 
  7. pop(key, default=None): Removes and returns an item with a specified key. If the key is not found, it returns the default value.

    d = {'a': 1, 'b': 2} print(d.pop('a')) # Output: 1 print(d.pop('c', 0)) # Output: 0 
  8. popitem(): Removes and returns the last (key, value) item pair from the dictionary.

    d = {'a': 1, 'b': 2} print(d.popitem()) # Output: ('b', 2) 
  9. setdefault(key, default=None): Returns the value of the specified key. If the key does not exist, inserts key with a value of default.

    d = {'a': 1} print(d.setdefault('a', 0)) # Output: 1 print(d.setdefault('b', 2)) # Output: 2 
  10. update([other]): Updates the dictionary with the key-value pairs from other. Overwrites existing keys.

    d = {'a': 1, 'b': 2} d.update({'b': 3, 'c': 4}) print(d) # Output: {'a': 1, 'b': 3, 'c': 4} 
  11. values(): Returns a view object that displays a list of all the values in the dictionary.

    d = {'a': 1, 'b': 2} print(list(d.values())) # Output: [1, 2] 

More Tags

angular-material2 select dylib virtualbox tcp-keepalive flutter-container masking google-docs angular-sanitizer spring-oauth2

More Programming Guides

Other Guides

More Programming Examples