Python – How to split string into a dict

Few Python examples to show you how to split a string into a dictionary. 1.1 Split a string into a dict. #!/usr/bin/python str = "key1=value1;key2=value2;key3=value3" d = dict(x.split("=") for x in str.split(";")) for k, v in d.items(): print(k, v) Output key1 value1 key2 value2 key3 value3 1.2 Convert two list into a dict. #!/usr/bin/python str1 …

Read more

Python – How to print dictionary

Python example to print the key value of a dictionary. stocks = { ‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54 } print(stocks) for k, v in stocks.items(): print(k, v) for k in stocks: print(k, stocks[k]) Output {‘IBM’: 146.48, ‘MSFT’: 44.11, ‘CSCO’: 25.54} IBM 146.48 MSFT 44.11 CSCO 25.54 IBM 146.48 MSFT 44.11 CSCO 25.54 References Python …

Read more

Python – How to loop a dictionary

In this tutorial, we will show you how to loop a dictionary in Python. 1. for key in dict: 1.1 To loop all the keys from a dictionary – for k in dict: for k in dict: print(k) 1.2 To loop every key and value from a dictionary – for k, v in dict.items(): for …

Read more

Python – Check if key exists in dictionary

In Python, you can use the in operator to check if a key exists in a dictionary. test.py def main(): fruits = { ‘apple’:1, ‘orange’:2, ‘banana’:3 } #if key ‘apple’ exists in fruits? if ‘apple’ in fruits: print(fruits[‘apple’]) if __name__ == ‘__main__’: main() Output 1 P.S Tested with Python 3.4.3 Note has_key() is deprecated in …

Read more