1+ Python 3.9 .1 (tags / v3 .9.1 :1e5 d33e , Dec 7 2020 , 17 :08 :21 ) [MSC v .1927 64 bit (AMD64 )] on win32
2+ Type "help" , "copyright" , "credits" or "license()" for more information .
3+ > >> f = open ("E:\\ Python\\ Beginner_Level\\ working with json\\ file.txt" ,'r' )
4+ >> > s = f .read ()
5+ >> > s
6+ '{"aspire_7": {"cpu": "i5-9300h", "gpu": "gtx 1650 4gb ddr5", "ram": "8gb", "refresh rate": "60hz", "weight": "2.2kg", "wifi ": 6}, "nitro_5": {"cpu": "r5-3500h", "gpu": "gtx 1650 4gb ddr5", "ram": "8gb", "refresh rate": "120hz", "weight": "2.5kg", "wifi ": 5}}'
7+ >> > # convert from json to dictionary
8+ >> > import json
9+ >> > laptop = json .loads (s )
10+ >> > laptop
11+ {'aspire_7' : {'cpu' : 'i5-9300h' , 'gpu' : 'gtx 1650 4gb ddr5' , 'ram' : '8gb' , 'refresh rate' : '60hz' , 'weight' : '2.2kg' , 'wifi ' : 6 }, 'nitro_5' : {'cpu' : 'r5-3500h' , 'gpu' : 'gtx 1650 4gb ddr5' , 'ram' : '8gb' , 'refresh rate' : '120hz' , 'weight' : '2.5kg' , 'wifi ' : 5 }}
12+ >> > # difference above 2 output is 1st one is json/string and 2nd one is dictionary
13+ >> > type (laptop )
14+ < class 'dict' >
15+ >> > type (s )
16+ < class 'str' >
17+ >> > laptop ['aspire_7' ]['gpu' ]
18+ 'gtx 1650 4gb ddr5'
19+ >> > laptop ['nitro_5' ]['' ]
20+ Traceback (most recent call last ):
21+ File "<pyshell#11>" , line 1 , in < module >
22+ laptop ['nitro_5' ]['' ]
23+ KeyError : ''
24+ > >> # to print weight of laptop in laptop dictionary
25+ >> > for weight in laptop :
26+ print (laptop ['weight' ])
27+
28+
29+ Traceback (most recent call last ):
30+ File "<pyshell#15>" , line 2 , in < module >
31+ print (laptop ['weight' ])
32+ KeyError : 'weight'
33+ > >> for weight in laptop :
34+ print (laptop [weight ])
35+
36+
37+ {'cpu' : 'i5-9300h' , 'gpu' : 'gtx 1650 4gb ddr5' , 'ram' : '8gb' , 'refresh rate' : '60hz' , 'weight' : '2.2kg' , 'wifi ' : 6 }
38+ {'cpu' : 'r5-3500h' , 'gpu' : 'gtx 1650 4gb ddr5' , 'ram' : '8gb' , 'refresh rate' : '120hz' , 'weight' : '2.5kg' , 'wifi ' : 5 }
39+ > >>
0 commit comments