Source: Payilagam Blog

Payilagam Blog Python – Dictionary Basics with Programs

Dictionary -> Key – Value Pair-> No Duplicate keys allowed-> Duplicate values are possible-> Heterogeneous objects for both keys and values allowed-> Insertion Order is not maintained-> Dictionaries are mutable-> Indexing and Slicing – not supported Dictionary Creation: d = {}d = dict()d[10] = ‘muthu’d[200] = ‘kavin’ d = {10:’muthu’,200:’kavin’} Accessing Data from Dictionary: print(d[100])print(d[2]) Program: Enter name and % in Dictionary register = {}n = int(input(“Enter no “))i = 1while i<=n:name = input()perc = input()register[name] = perci+=1 for x in register:print(“\t”, x, “\t\t”, register[x]) Update Dictionaries: d[key] = valued = {100:’muthu’,200:’kavin’}print(d)d[300] = ‘viyan’print(d)d[100] = ‘navilan’print(d) Delete Elements from Dictionary del d[key] del d[100] clear() d.clear() del d to delete total dictionary Functions 1 dict() d = dict([(100,’muthu’), (200,’muthu’)]) 2 len() 3 clear() 4 get(key) d.get(key) print(d[100]) #muthuஇல்லாத keyஐக் கொடுத்தால்,print(d[1000]) #keyerror print(d.get(1000)) #None 5 pop(key) removes the entry with the given key and returns the corresponding value If key is not present, KeyError will be thrown. popitem() ஏதாவது ஒரு key-valueஐ நீக்கித் தரும். d = {100:”muthu”, 200:”Kavin”}print(d) print(d.popitem())print(d) 7 keys() d = {100:”muthu”, 200:”kavin”}print(d.keys())for k in d.keys():print(k) 8 values() print(d.values())for v in d.values():print(v) 9 items() returns list of tuples representing key-value pairsfor k,v in d.items():print(k,”–“, v) for it in d.items():print(it)print(type(it)) for i in d:print(i) 10 copy() d2 = d.copy() 11 setdefault() d.setdefault(k,v)இங்கு key ஏற்கெனவே இருந்தால், function returns corresponding value. key இல்லை எனில் specified key-vaue, புது item ஆக dictionaryஇல் சேர்க்கப்படும். 12 update() d.update(x)All items present in the dictionary will be added to dictionary d 13 get d = {‘Name’:’Muthu’, ‘Age’: 50}print(d.get(‘Age’))print(d.get(‘Salary’))print(d.get(‘Salary’,’Not available’)) Programs Take dictionary from keyboard and print sum of values d = eval(input(“Enter dictionary “))s = sum(d.values())print(s) 2 Number of occurrences of each letter word = input(“Enter any word “)d = {}for x in word:d[x] […] The post Python – Dictionary Basics with Programs appeared first on Payilagam | Java | PYTHON | Selenium| | Android | .NET| Best Training in Chennai.

Read full article »
Est. Annual Revenue
$100K-5.0M
Est. Employees
1-25
CEO Avatar

CEO

Update CEO

CEO Approval Rating

- -/100