Python-Dictionary-IQ

What is dict Data Type?
If we want to represent a group of values as key-value pairs then we should go for dict data type.
Eg:
d={101:’John’,102:’Comfort’,103:’Ico’}
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value.

dict is mutable and the order wont be preserved.

If we want to represent a group of objects as key-value pairs then what will we use in Python?

Dictionary.If we want to represent a group of objects as key-value pairs then we can use Dictionary in Python.

What are the characteristics of Dictionary in python?
  • Duplicate keys are not allowed but values can be duplicated.
  • Heterogeneous objects are allowed for both keys and values.
  • insertion order is not preserved
  • Dictionaries are mutable
  • Dictionaries are dynamic
  • indexing and slicing concepts are not applicable
How to create a Dictionary?

Dictionaries are written with curly brackets, and have keys and values:Create and print a dictionary:

thisdict = {
"brand": "car",
"model": "car",
"year": 1964
}
print(thisdict)

How to access data from the dictionary?

We can access data by using keys.
d={100:’vikas’ ,200:’ram’, 300:’cloud’}
print(d[100]) #vikas
print(d[300]) #cloud
if 400 in d:
print(d[400])

How to delete elements from dictionary?
del d[key]
It deletes entry associated with the specified key.
If the key is not available then we will get KeyError
Eg:

  1. d={100:”vikas”,200:”cloud”,300:”hadoop”}
  2. print(d)
  3. del d[100]

d.clear()
To remove all entries from the dictionary
Eg:

  1. d={100:”vikas”,200:”cloud”,300:”hadoop”}
  2. print(d)
  3. d.clear()

del d
To delete total dictionary.Now we cannot access d
Eg:

  1. d={100:”vikas”,200:”cloud”,300:”hadoop”}
  2. print(d)
  3. del d
  4. print(d)
    5.
  5. Output
  6. {100: ‘vikas’, 200: ‘cloud’, 300: ‘hadoop’}
  7. NameError: name ‘d’ is not defined

Important functions of dictionary:

  1. dict():
    To create a dictionary
    d=dict() ===>It creates empty dictionary
    d=dict({100:”vikas”,200:”cloud”}) ==>It creates dictionary with specified elements
    d=dict([(100,”vikas”),(200,”hadoop”),(300,”cloud”)])==>It creates dictionary with the given
    list of tuple elements
  2. len()
    Returns the number of items in the dictionary
  3. clear():
    To remove all elements from the dictionary
  4. get():
    To get the value associated with the key
    d.get(key)
    If the key is available then returns the corresponding value otherwise returns None.It
    wont raise any error.
    d.get(key,defaultvalue)
    If the key is available then returns the corresponding value otherwise returns default
    value.
  5. pop():
    d.pop(key)
    It removes the entry associated with the specified key and returns the corresponding
    value
    If the specified key is not available then we will get KeyError

popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.

If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: ‘popitem(): dictionary is empty’

keys():
It returns all keys associated with the dictionary

values():
It returns all values associated with the dictionary

items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]

copy():
To create exactly duplicate dictionary(cloned copy)
d1=d.copy();

setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new item to the
dictionary.

update():
d.update(x)
All items present in the dictionary x will be added to dictionary d

*************************************************************

True or False:
Dictionary elements can be accessed using position-based index.
Answer -False

Dictionaries are immutable.
Answer-False

courses.clear() will delete the dictionary object called courses.
Answer-False

It is possible to nest dictionaries.
Answer-True

It is possible to hold multiple values against a key in a dictionary.
Answer-True

*******************************************************

Write a program to find number of occurrences of each letter present in
the given string?
  1. word=input(“Enter any word: “)
  2. d={}
  3. for x in word:
  4. d[x]=d.get(x,0)+1
  5. for k,v in d.items():
  6. print(k,”occurred “,v,” times”)

other way:

s = input(‘Enter any string:’)
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print (‘Count of all characters is: ‘, freq)

for k, v in freq.items():
print(k, ‘:’, end = ”)
for i in range(0, v):
print(‘*’, end =”)
print()

Write a program to find number of occurrences of each vowel present in
the given string?
  1. word=input(“Enter any word: “)
  2. vowels={‘a’,’e’,’i’,’o’,’u’}
  3. d={}
  4. for x in word:
  5. if x in vowels:
  6. d[x]=d.get(x,0)+1
  7. for k,v in sorted(d.items()):
  8. print(k,”occurred “,v,” times”)
Write a program to accept student names and marks from the keyboard
and creates a dictionary. Also, display student marks by taking student name as input?

1) n=int(input(“Enter the number of students: “))
2) d={}
3) for i in range(n):
4) name=input(“Enter Student Name: “)
5) marks=input(“Enter Student Marks: “)
6) d[name]=marks
7) while True:
8) name=input(“Enter Student Name to get Marks: “)
9) marks=d.get(name,-1)
10) if marks== -1:
11) print(“Student Not Found”)
12) else:
13) print(“The Marks of”,name,”are”,marks)
14) option=input(“Do you want to find another student marks[Yes|No]”)
15) if option==”No”:
16) break
17) print(“Thanks for using our application”)

Dictionary-problem