-1

This is my code:

response = requests.get(url,params=datas)
data = response.json()
price=data["bids"]
print(price)

Output of the code:

{'31833.94000000': '0.02832100', '31833.93000000': '0.01291000', '31833.91000000': '0.09935100', '31833.90000000': '0.10243500', '31833.52000000': '0.01751100', '31833.38000000': '0.03296200', '31831.66000000': '0.00148000', '31831.24000000': '0.17640200', '31831.23000000': '0.84000000', '31830.79000000': '0.00044800', '31830.02000000': '0.70980400', ...

  • Data changes every time I receive them.
  • How can I copy only the first element?
Jakub Szlaur
  • 1,852
  • 10
  • 39
Aldo
  • 1
  • This is just a guess, since I did not quite understand your question neither the context, but what you might be looking is a deep copy: https://stackoverflow.com/a/5105554/4868875 – Berthin Jan 24 '21 at 22:44
  • 1
    That is not a "json object", that is the *result* of deserializing JSON into *python objects*, in this case, you have a `dict`. Note, `dict` objects maintain insertion order, however, the JSON standard says that JSON objects, which is what the `dict` comes from *are unordered*. Does the API really use the *order* of the JSON obejct? – juanpa.arrivillaga Jan 24 '21 at 22:45
  • In the api page: This API provides with a sorted list (in descending order) of bids and asks. They are ordered from the newest to oldest price, there is a way to copy only the first price so i can make an order with it? – Aldo Jan 24 '21 at 22:51
  • 1
    @Aldo: What's shown in your question is not a list, it's a Python dictionary which corresponds to a JSON "object" which is "An _unordered_ set of name/value pairs." (see [JSON spec](https://www.json.org/json-en.html)). – martineau Jan 24 '21 at 22:53

3 Answers3

0

Try importing the json into an ordered dictionary (odict) and then read the value by index.

http://dl.ubnt.com/RouterStationChallenge/PyCI/docs/PyCI/odict.html

0

It worked, thank you

    response = requests.get(url,params=datas)
    data = response.json()
    price=collections.OrderedDict(data["bids"])
    first=list(price)[:1]
    print(first)

but there is a fastest way?

Aldo
  • 1
0

if we assume by the first element you mean: '31833.94000000': '0.02832100', you can store it as a tuple like this:

first_element = [(k,v) for (k,v) in data["bids"].items()][0]