Dictionary manipulation

  • Mutable Data type

  • syntax: d = {key:value}, d = dict(), d = {}

  • Duplicates Key not allowed

  • Duplicates Values allowed

  • Heterogeneous values are allowed for both k,v

  • No array means no indexing

  • Insertion order not maintained



d = dict()

print(type(d))

d = {}

print(type(d))


d = {"a":"Apple","b":"Ball"}

print(d)

d = {"a":"Apple",2:"Ball",3:[4,7,(3,6)]}

print(d)


Accessing Elements from dictionary

   1. using [key_name]

  • if we try to access key_name that is not present in dic then it throws keyerror.

   2. using get(key_name)

  • if we try to access key_name that doesn't exist in dic then it does not throw any error.

       

print(d["a"])

print(d.get("a"))

print(d.get("c"))

#print(d["c"]) #keyerror

          

       Update And Add elements from Dictionary

  • using Assignment operator we are able to add or change the element. If the key is present then value will be updated otherwise new element is added with key:value.

d["a"] = "Amazon"

print(d)

d["c"] = "Cat"

print(d)

     Remove the Key
    1. pop(key)

  • Used to remove the provided key from the dictionary and return the value.

  • If key not available and you try to remove it throw keyerror

  • It return data type is based on value.

    2.popitem()

  • Used to remove the arbitrary element and return the removed key and value as a tuple data type.

  • It return tuple data type.

    3. clear()

  • Used to remove all elements from dictionary

  • It return none

   4. del dict_name

  • Used to remove the dictionary. Removed from memory as well


print(d.pop("c"))

 #print(d.pop("c"))#if key not available

print(d.popitem())

print(d.clear())

print(d)

del d

#print(d)



fromkeys(), keys() and items(), update()
   

  1. fromkeys(sequence,value) 

   It creates a new dictionary with a given sequence of elements with a value provided by the user if value is not present then value is set as a none.
    

              

seq = {'1','2','3','4'}

print(type(seq))

print(dict.fromkeys(seq,'number'))


print(dict.fromkeys(seq))


#mutable object issue

val = ["num1"]

dict1 = dict.fromkeys(seq,val)

print(dict1)

val.append("num2")

print(dict1)


This happens because each element is assigned a reference to the same object (points to the same object in the memory).


To avoid this issue, we use dictionary comprehension.


2.keys()

  • this method returns all keys from given dictionary.

  •  If we get all keys from dictionary and saved in one variable and after that we add one key in dictionary that time variable data also get changed

   

numKeys = dict1.keys()

print(numKeys)


#after update

dict1.update({'5':"num2"})

print(numKeys)

print(dict1)


 3.items()

  • The items() method returns a view object that displays a list of dictionary's (key, value) tuple pairs.


numItems = dict1.items()

print(numItems)


#after update

dict1.update({'6':"num2"})

print(numItems)



setdefault(key,value(optional))

  • This method returns the value of a key if the key is in the dictionary. If not, it inserts a key with a value if the value is not assigned then sets none.

default1 = dict1.setdefault("6")

print(default1)

#if Not withoutvalue

default1 = dict1.setdefault("8")

print(default1)

#if Not withvalue

default1 = dict1.setdefault("9",'num1')

print(default1)


Categories: Python Tags: #Python,

Comments