Python 3x Pandas Django

Dictionaries

thisdict = {
  "name": "John",
  "state": "New York",
  "dob": 1990 }

Dictionaries are written with curly brackets { }, and have keys and values

A dictionary is ordered (starts from python version 3.7), changeable and does not allow duplicates

Dictionary Items

Dictionary items are presented in key:value pairs

Dictionary items are ordered, changeable, and does not allow duplicates (i.e) dictionaries cannot have two items with the same key

  thisdict = {
    "name": "John",
    "state": "New York",
    "dob": 1990 }

  print(thisdict["name"])     #Output: John
  print(thisdict["state"])    #Output: New York
  print(thisdict["dob"])      #Output: 1990

Changeable

  thisdict = {
    "name": "John",
    "state": "New York",
    "dob": 1990 }

  thisdict["name"] = "John Michael"
  print(thisdict["name"])     #Output: John Michael
  thisdict["state"] = "Texas"
  print(thisdict["state"])    #Output: Texas
  thisdict["dob"] = "1991"
  print(thisdict["dob"])      #Output: 1991

Does not allow duplicates in dictionaries

thisdict = {
    "name": "John",
    "state": "New York",
    "dob": 1990,
    "dob": 1991 }
print(thisdict)  #Output: {'name': 'John', 'state': 'New York', 'dob': 1991}

"dob": 1990 override with "dob": 1991 and the above output will become {'name': 'John', 'state': 'New York', 'dob': 1991}

Adding new:value pair in an existing dictionaries

thisdict = {
    "name": "John",
    "state": "New York",
    "dob": 1990}
thisdict["fullname"] = "John Michael"
print(thisdict)

#Output: {'name': 'John', 'state': 'New York', 'dob': 1990, 'fullname': 'John Michael'}

dict()

dict() is a built-in function used to create a dictionary

mydict = dict(name='John',
              age=10,
              is_activate=True)
print(mydict)   #Output: {'name': 'John', 'age': 10, 'is_activate': True}

Dictionary ? yes

mydict = {
  'a': [1,2,3,4,5],
  'b': True,
  'c': {'ones':[1,11,111,1111],
        'twos':2}
}

print(mydict['c']['ones'][3])    #Output: 1111

Some Important Python Dictionary Methods

MethodsDescription
clear()Removes all items from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()Creates a new dictionary from the given sequence of elements with a value provided
get()Returns the value for the specified key if key is in dictionary
items()Returns a view object that displays a list of dictionary's (key, value) tuple pairs
keys()Returns a view object that displays a list of all the keys in the dictionary
popitem()Removes and returns the last element (key, value) pair
setdefault()Returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary
pop()Removes and returns an element from a dictionary having the given key
values()Returns a view object that displays a list of all the values in the dictionary
update()Updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs

clear()

  thisdict = {
      "name": "John",
      "state": "New York",
      "dob": 1990}
   thisdict.clear()    #removes all items from the dictionary

  print(thisdict)   #Output: {}


copy()

  thisdict = {
      "name": "John",
      "state": "New York",
      "dob": 1990}
  newdict = thisdict.copy() #returns a shallow copy of the dictionary

  print(newdict)   #Output: {'name': 'John', 'state': 'New York', 'dob': 1990}


fromkeys()

fromkeys() method takes two parameters

sequence - sequence of elements which is to be used as keys for the new dictionary

value (Optional) - value which is set to each each element of the dictionary

dictionary.fromkeys(sequence[, value])

Create a dictionary from a sequence of keys with value

keys = {'a', 'e', 'i', 'o', 'u' }

vowels = dict.fromkeys(keys)
print(vowels)   #Output: {'i': None, 'a': None, 'e': None, 'u': None, 'o': None}

Create a dictionary from a sequence of keys with same value

keys = {'a', 'e', 'i', 'o', 'u' }
value = 'vowel'

vowels = dict.fromkeys(keys, value) 
print(vowels)     #Output {'i': 'vowel', 'a': 'vowel', 'e': 'vowel', 'u': 'vowel', 'o': 'vowel'}


get()

returns the value for the specified key if key is in dictionary

dict.get(key[, value])

thisdict = {
       "name": "John",
       "state": "New York",
       "dob": 1990}

x = thisdict.get("name")
print(x)    #Output: John


items()

displays a list of dictionary's (key, value) tuple pairs

thisdict = {
     "name": "John",
     "state": "New York",
     "dob": 1990}

print(thisdict.items()) #Output dict_items([('name', 'John'), ('state', 'New York'), ('dob', 1990)])


keys()

displays a list of all the keys in the dictionary

thisdict = {
     "name": "John",
     "state": "New York",
     "dob": 1990}

print(thisdict.keys())  #Output: dict_keys(['name', 'state', 'dob'])

empty_dict = {}
print(empty_dict.keys())    #Output: dict_keys([])


popitems()

Returns the latest inserted element (key,value) pair from the dictionary.

Removes the returned element pair from the dictionary.

thisdict = {
      "name": "John",
      "state": "New York",
      "dob": 1990}

result = thisdict.popitem()

# return last instered pair (key, value) in tuple form
print(result)       #Output: ('dob', 1990)

# removed that items from thisdict
print(thisdict)     #Output: {'name': 'John', 'state': 'New York'}


setdefault()

fromkeys() method takes two parameters

  • key - the key to be searched in the dictionary
  • default_value (optional) - key with a value default_value is inserted into the dictionary if the key is not in the dictionary.
    If not provided, the default_value will be None.
dict.setdefault(key[, default_value])

Get the value of the "gender" item, if the "gender" item does not exist, insert "gender" with the value "male"

thisdict = {
       "name": "John",
       "state": "New York",
       "dob": 1990}
x = thisdict.setdefault("gender", "male")

print(x)        #Output: male


pop()

removes and returns an element from a dictionary having the given key

dictionary.pop(key[, default])

thisdict = {
     "name": "John",
     "state": "New York",
     "dob": 1990}


element = thisdict.pop('state')
print('The popped element is:', element)    #Output: New York
print('The dictionary is:', thisdict)       #Output: {'name': 'John', 'dob': 1990}

Pop an element for the given key

thisdict = {
     "name": "John",
     "state": "New York",
     "dob": 1990}


element = thisdict.pop('state')
print('The popped element is:', element)    #Output: New York
print('The dictionary is:', thisdict)       #Output: {'name': 'John', 'dob': 1990}


values()

displays a list of all values in a given dictionary

thisdict = {
     "name": "John",
     "state": "New York",
     "dob": 1990}

print(thisdict.values()) #Output: dict_values(['John', 'New York', 1990])


update()

update() method adds element(s) to the dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value

thisdict = {
    "name": "John",
    "state": "New York",
    "dob": 1990}

# updates the value of key 'dob'
thisdict.update({"dob": 1980})
print(thisdict)    #Output: {'name': 'John', 'state': 'New York', 'dob': 1980}

new_element = {"gender": "male"}

# adds new key:value pair
thisdict.update(new_element)
print(thisdict)    #Output: {'name': 'John', 'state': 'New York', 'dob': 1980, 'gender': 'male'}


If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!