Home > Software engineering >  how to extract get items out of a dict
how to extract get items out of a dict

Time:12-10

I have a dict that looks like this stored in a variable bookR

{'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}
{'User-ID': '2345635', 'ISBN': '3456477588844', 'Rating': '5'}
{'User-ID': '2345632', 'ISBN': '9890876776388', 'Rating': '4'}
{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}

i want to extract two and store them in different variable as userA and userB

i have tried this but it gave keyerror code

print(bookR)

userA = bookR[1]

userB = bookR[4]

print(userA)
print(userB)

but the result i need is

print(userA)
output: {'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}

print(userB)
output:{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}

CodePudding user response:

I think this is what you are trying to do:

  • each dictionary forms an item in the list called bookR
bookR = [{'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'},    
         {'User-ID': '2345635', 'ISBN': '3456477588844', 'Rating': '5'},
         {'User-ID': '2345632', 'ISBN': '9890876776388', 'Rating': '4'},
         {'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}]

userA = bookR[0]
userB = bookR[3]

print("user A:", userA)
print("user B:", userB)

Output:

user A: {'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'}
user B: {'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}

Note:

Lists use a zero index... which means the first item is at index 0

CodePudding user response:

First of all: index 1 of an array is not the first item in it, but the second. So if you do k = [1,2,3,4] print(k[1]) it prints 2. And the second thing I found in your code is that you need to set commas between the items of your array. After these two things fixed your code should look like this:

bookR = [{'User-ID': '2345667', 'ISBN': '265838929355X', 'Rating': '0'},
{'User-ID': '2345635', 'ISBN': '3456477588844', 'Rating': '5'},
{'User-ID': '2345632', 'ISBN': '9890876776388', 'Rating': '4'},
{'User-ID': '2767888', 'ISBN': '2234566663200', 'Rating': '7'}]

print(bookR)

userA = bookR[0]

userB = bookR[3]

print(userA)
print(userB)
  • Related