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.
# Create a new dictionary d = dict() # or d = {} # Add a key - value pairs to dictionary d['xyz'] = 123d['abc'] = 345 # print the whole dictionary print(d) # print only the keys print(d.keys()) # print only values print(d.values()) # iterate over dictionary for i in d : print("%s %d" %(i, d[i])) # another method of iteration for index, value in enumerate(d): print (index, value , d[value]) # check if key exist print('xyz' in d) # delete the key-value pair del d['xyz'] # check again print("xyz" in d) |
Output:
{'xyz': 123, 'abc': 345}
['xyz', 'abc']
[123, 345]
xyz 123
abc 345
0 xyz 123
1 abc 345
True
False
Dictionary Programs, Built-in Functions
- Dict.cmp(): Compares elements of both dict.
- Dict.len(): Gives the total length of the dictionary.
- Dict.str(): Produces a printable string representation of a dictionary.
- Dict.type(): Returns the type of the passed variable.
- Dict.clear(): Removes all elements of dictionary dict
- Dict.copy(): Returns a shallow copy of dictionary dict
- Dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.
- Dict.get(): For key, returns value or default if key not in dictionary
- Dict.has_key(): Returns true if key in dictionary dict, false otherwise
- Dict.items(): Returns a list of dict’s (key, value) tuple pairs
- Dict.keys(): Returns list of dictionary dict’s keys
- Dict.setdefault(): Set dict[key]=default if key is not already in dict
- Dict.update(): Adds dictionary dict2’s key-values pairs to dict
- Dict.values(): Returns list of dictionary dict’s values
- Dictionary Methods – Set 1,Set 2
- Output questions on dictionary
- Get() method for dictionaries
- Handling missing keys of dictionary
- Ordered Dictionary
- Majority Element
- Dictionary and counter in Python to find winner of election
- How to implement Dictionary with Python3
- Possible Words using given characters in Python
- Python dictionary, set and counter to check if frequencies can become same
- Python dictionary intersection
- OrderedDict() in Python
- Merging two Dictionaries
- Chainmap
- orderDict()
Useful Links
- Output of Python programs – Dictionary
- Output of Python programs – Dictionary
- Recent Articles on Python Dictionary
- Coding Practice Platform
- Multiple Choice Questions – Python
- All articles in Python Category


