-1

Suppose I got a dictionary from an api as:

book_data = {'book name':'abc','author name':'john doe','book version':'12','book number':'19','book price':'200'}

I only want the data of 'book name', 'author name' and 'book price', for this I did,

filtered_book_data = {key: book_data[key] for key in book_data.keys() & {"book name", "author name", "book price"}}

But while printing, filtered_book_data,

it prints either :

{'book name' : 'abc', 'author name' : 'john doe', 'book price' : '200'} or
{'author name' : 'john doe' 'book name' : 'abc' , 'book price' : '200'} or
{'book price' : '200' , 'author name' : 'john doe' 'book name' : 'abc' } or so on

But it's not fixes, but I want the O/P to be always:

{'book name' : 'abc', 'author name' : 'john doe', 'book price' : '200'}

book name, author name, book price always in that order.

How can I fix the position of dictionary?

Siva Pradhan
  • 791
  • 1
  • 6
  • 23

1 Answers1

1

You could reorganize it like this. It uses a reference list.

order = ['book name','author name','book price']
weird = {'book price' : '200' , 'author name' : 'john doe', 'book name' : 'abc' } 
good = {k:weird.get(k) for k in order}
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44