Python - Dictionary Questions Flashcards

1
Q

Dictionary?

A

In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Create a new dictionary

A
# Create a new dictionary 
d = dict() 
# or you can do 
d = {}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Add a key - value pairs to dictionary

A
# Add a key - value pairs to dictionary
d['xyz'] = 123
d['abc'] = 345

returns {‘xyz’: 123, ‘abc’: 345}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

print the whole dictionary

A
# print the whole dictionary
print(d)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

print only the keys

A
# print only the keys
print(d.keys())
returns ['key1', 'key2',...]
#notice the parens around the keys
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

print only values

A
# print only values
print(d.values())
returns [value1, value2]
#notice the lack of parens around the values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

iterate over dictionary

A
# iterate over dictionary
for i in d :
    print("%s  %d" %( i, d[i] ) )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

another way of iteration over a dictionary

A
# another method of iteration
for index, value in enumerate(d):
    print (index, value , d[value])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

check if key exist

A
# check if key exist
print('xyz' in d)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

delete the key-value pair

A
# delete the key-value pair
del d['xyz']
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Dict.cmp()

A

Dict.cmp(): Compares elements of both dict.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Dict.len()

A

Dict.len(): Gives the total length of the dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Dict.str()

A

Dict.str(): Produces a printable string representation of a dictionary.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Dict.type()

A

Dict.type(): Returns the type of the passed variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Dict.clear()

A

Dict.clear(): Removes all elements of dictionary dict

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Dict.copy()

A

Dict.copy(): Returns a shallow copy of dictionary dict

17
Q

Dict.fromkeys()

A

Dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.

18
Q

Dict.get()

A

Dict.get(): For key, returns value or default if key not in dictionary

Dict.get(key, default=None)

19
Q

Dict.has_key()

A

Dict.has_key(): Returns true if key in dictionary dict, false otherwise

20
Q

Dict.items()

A

Dict.items(): Returns a list of dict’s (key, value) tuple pairs

21
Q

Dict.keys()

A

Dict.keys(): Returns list of dictionary dict’s keys

22
Q

Dict.setdefault()

A

Dict.setdefault(): Set dict[key]=default if key is not already in dict

23
Q

Dict.update()

A

Dict.update(): Adds dictionary dict2’s key-values pairs to dict

24
Q

Dict.values()

A

Dict.values(): Returns list of dictionary dict’s values

25
Q

dic = {“A”:1, “B”:2}

How would we access the above values?

A

dic = {“A”:1, “B”:2}
print(dic.get(“A”))
print(dic.get(“C”))
print(dic.get(“C”,”Not Found ! “))

26
Q

Given three arrays sorted in non-decreasing order, print all common elements in these arrays.

ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
A

First convert all three lists into dictionaries having elements as keys and their frequencies as value, using Counter() method.

Now perform intersection operation for three dictionaries, this will result us dictionary having common elements among three array list with their frequencies.

# Function to find common elements in three
# sorted arrays
from collections import Counter
def commonElement(ar1,ar2,ar3):
     # first convert lists into dictionary
     ar1 = Counter(ar1)
     ar2 = Counter(ar2)
     ar3 = Counter(ar3)
     # perform intersection operation
     resultDict = dict(ar1.items() & ar2.items() & ar3.items())
     common = []
 # iterate through resultant dictionary
 # and collect common elements
 for (key,val) in resultDict.items():
      for i in range(0,val):
           common.append(key)

 print(common)
# Driver program
if \_\_name\_\_ == "\_\_main\_\_":
    ar1 = [1, 5, 10, 20, 40, 80]
    ar2 = [6, 7, 20, 80, 100]
    ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
    commonElement(ar1,ar2,ar3)
#Output
[80, 20]
27
Q

How to merge two dictionaries using update() ?

A

Using the method update()

By using the method update() in Python, one list can be merged into another. But in this, the second list is merged into the first list and no new list is created. It returns None.
Example:
# Python code to merge dict using update() method
def Merge(dict1, dict2):
    return(dict2.update(dict1))
# Driver code
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
# This return None
print(Merge(dict1, dict2))
# changes made in dict2
print(dict2)
28
Q

How to merge two dictionaries using ** ?

A

Using ** in Python

# Python code to merge dict using a single 
# expression
dict1 = {'a':1, 'b':2}
dict2 = {'c':3, 'd':4}

dict3 = {**dict1, **dict2}
_________________

This is generally considered a trick in Python where a single expression is used to merge two dictionaries and stored in a third dictionary. The single expression is **. This does not affect the other two dictionaries. ** implies that the argument is a dictionary. Using ** [double star] is a shortcut that allows you to pass multiple arguments to a function directly using a dictionary. For more information refer **kwargs in Python. Using this we first pass all the elements of the first dictionary into the third one and then pass the second dictionary into the third. This will replace the duplicate keys of the first dictionary.