Extract info when JSON when key changes in Python - python
I'm quite new to Python so please excuse me if my terminology is not 100% accurate or if this is quite simple
I currently have the code:
import requests
POINTS = requests.get('https://api.torn.com/market/?selections=pointsmarket&key=jtauOcpEwz0W0V5M').json()
POINTSA = POINTS['pointsmarket']
print (POINTSA)
I want to print the cost of the very first key. However, the number for the first key will always change.
At the time of posting the first key is 9765126 as seen here:
https://imgur.com/VRi8Owe
So the line would be (I think):
POINTSA = POINTS['pointsmarket'][9765126]['cost']
However in 5 minutes time, the 9765126 key will change to something else. How do I get it to print the 1st cost entry regardless of the first key?
Hi you can try the following sample of getting the keys as a list then getting the first index
keys = list(POINTS['pointsmarket'].keys()) # Get all keys and convert to a list
POINTS['pointsmarket'][keys[0]]['cost']
Related
Looping through json.loads(response.text) with Python
i'm learning and would appreciate any help in this code. The issue is trying to print the values in the data that are contained in one line of the JSON using Python. import json import requests data = json.loads(response.text) print(len(data)) #showing correct value #where i'm going wrong below obviously this will print the first value then the second as it's indexed. Q how do I print all values when using seperate print statements when the total indexed value is unknown? for item in data: print(data[0]['full_name']) print(data[1]['full_name']) I tried without the index value this gave me the first value multiple times depending on the length. I expect to be able to access from the JSON file each indexed value separately even though they are named the same thing "full_name" for example.
import json import requests data = json.loads(response.text) print(len(data)) #showing correct value for item in data: print(item['full_name']) #the below code will throw error.. because python index starts with 0 print(data[0]['full_name']) print(data[1]['full_name']) hope this help
Presuming data is a list of dictionaries, where each dictionary contains a full_name key: for item in data: print(item['full_name']) This code sample from your post makes no sense: for item in data: print(data[0]['full_name']) print(data[1]['full_name']) Firstly it's a syntax error because there is nothing indented underneath the loop. Secondly it's a logic error, because the loop variable is item but then you never refer to that variable.
Python- Insert new values into 'nested' list?
What I'm trying to do isn't a huge problem in php, but I can't find much assistance for Python. In simple terms, from a list which produces output as follows: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765}... All I want to do is add in an extra field, containing the 'runner name' in the data set below, into each of the 'runners' sub lists from the initial data set, based on selection_id=selectionId. So initially I iterate through the full dataset, and then create a separate list to get the runner name from the runner id (I should point out that runnerId===selectionId===selection_id, no idea why there are multiple names are used), this works fine and the code is shown below: for market_book in market_books: market_catalogues = trading.betting.list_market_catalogue( market_projection=["RUNNER_DESCRIPTION", "RUNNER_METADATA", "COMPETITION", "EVENT", "EVENT_TYPE", "MARKET_DESCRIPTION", "MARKET_START_TIME"], filter=betfairlightweight.filters.market_filter( market_ids=[market_book.market_id], ), max_results=100) data = [] for market_catalogue in market_catalogues: for runner in market_catalogue.runners: data.append( (runner.selection_id, runner.runner_name) ) So as you can see I have the data in data[], but what I need to do is add it to the initial data set, based on the selection_id. I'm more comfortable with Php or Javascript, so apologies if this seems a bit simplistic, but the code snippets I've found on-line only seem to assist with very simple Python lists and nothing 'nested' (to me the structure seems similar to a nested array). As per the request below, here is the full list: {"marketId":"1.130856098","totalAvailable":null,"isMarketDataDelayed":null,"lastMatchTime":null,"betDelay":0,"version":2576584033,"complete":true,"runnersVoidable":false,"totalMatched":null,"status":"OPEN","bspReconciled":false,"crossMatching":false,"inplay":false,"numberOfWinners":1,"numberOfRunners":10,"numberOfActiveRunners":8,"runners":[{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":2.8,"size":34.16},{"price":2.76,"size":200},{"price":2.5,"size":237.85}],"availableToLay":[{"price":2.94,"size":6.03},{"price":2.96,"size":10.82},{"price":3,"size":33.45}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832765},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":20,"size":3},{"price":19.5,"size":26.36},{"price":19,"size":2}],"availableToLay":[{"price":21,"size":13},{"price":22,"size":2},{"price":23,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832767},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":11,"size":9.75},{"price":10.5,"size":3},{"price":10,"size":28.18}],"availableToLay":[{"price":11.5,"size":12},{"price":13.5,"size":2},{"price":14,"size":7.75}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832766},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":48,"size":2},{"price":46,"size":5},{"price":42,"size":5}],"availableToLay":[{"price":60,"size":7},{"price":70,"size":5},{"price":75,"size":10}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832769},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":18.5,"size":28.94},{"price":18,"size":5},{"price":17.5,"size":3}],"availableToLay":[{"price":21,"size":20},{"price":23,"size":2},{"price":24,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832768},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":4.3,"size":9},{"price":4.2,"size":257.98},{"price":4.1,"size":51.1}],"availableToLay":[{"price":4.4,"size":20.97},{"price":4.5,"size":30},{"price":4.6,"size":16}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832771},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":24,"size":6.75},{"price":23,"size":2},{"price":22,"size":2}],"availableToLay":[{"price":26,"size":2},{"price":27,"size":2},{"price":28,"size":2}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":12832770},{"status":"ACTIVE","ex":{"tradedVolume":[],"availableToBack":[{"price":5.7,"size":149.33},{"price":5.5,"size":29.41},{"price":5.4,"size":5}],"availableToLay":[{"price":6,"size":85},{"price":6.6,"size":5},{"price":6.8,"size":5}]},"sp":{"nearPrice":null,"farPrice":null,"backStakeTaken":[],"layLiabilityTaken":[],"actualSP":null},"adjustmentFactor":null,"removalDate":null,"lastPriceTraded":null,"handicap":0,"totalMatched":null,"selectionId":10064909}],"publishTime":1551612312125,"priceLadderDefinition":{"type":"CLASSIC"},"keyLineDescription":null,"marketDefinition":{"bspMarket":false,"turnInPlayEnabled":false,"persistenceEnabled":false,"marketBaseRate":5,"eventId":"28180290","eventTypeId":"2378961","numberOfWinners":1,"bettingType":"ODDS","marketType":"NONSPORT","marketTime":"2019-03-29T00:00:00.000Z","suspendTime":"2019-03-29T00:00:00.000Z","bspReconciled":false,"complete":true,"inPlay":false,"crossMatching":false,"runnersVoidable":false,"numberOfActiveRunners":8,"betDelay":0,"status":"OPEN","runners":[{"status":"ACTIVE","sortPriority":1,"id":10064909},{"status":"ACTIVE","sortPriority":2,"id":12832765},{"status":"ACTIVE","sortPriority":3,"id":12832766},{"status":"ACTIVE","sortPriority":4,"id":12832767},{"status":"ACTIVE","sortPriority":5,"id":12832768},{"status":"ACTIVE","sortPriority":6,"id":12832770},{"status":"ACTIVE","sortPriority":7,"id":12832769},{"status":"ACTIVE","sortPriority":8,"id":12832771},{"status":"LOSER","sortPriority":9,"id":10317013},{"status":"LOSER","sortPriority":10,"id":10317010}],"regulators":["MR_INT"],"countryCode":"GB","discountAllowed":true,"timezone":"Europe\/London","openDate":"2019-03-29T00:00:00.000Z","version":2576584033,"priceLadderDefinition":{"type":"CLASSIC"}}}
i think i understand what you are trying to do now first hold your data as a python object (you gave us a json object) import json my_data = json.loads(my_json_string) for item in my_data['runners']: item['selectionId'] = [item['selectionId'], my_name_here] the thing is that my_data['runners'][i]['selectionId'] is a string, unless you want to concat the name and the id together, you should turn it into a list or even a dictionary each item is a dicitonary so you can always also a new keys to it item['new_key'] = my_value
So, essentially this works...with one exception...I can see from the print(...) in the loop that the attribute is updated, however what I can't seem to do is then see this update outside the loop. mkt_runners = [] for market_catalogue in market_catalogues: for r in market_catalogue.runners: mkt_runners.append((r.selection_id, r.runner_name)) for market_book in market_books: for runner in market_book.runners: for x in mkt_runners: if runner.selection_id in x: setattr(runner, 'x', x[1]) print(market_book.market_id, runner.x, runner.selection_id) print(market_book.json()) So the print(market_book.market_id.... displays as expected, but when I print the whole list it shows the un-updated version. I can't seem to find an obvious solution, which is odd, as it seems like a really simple thing (I tried messing around with indents, in case that was the problem, but it doesn't seem to be, its like its not refreshing the market_book list post update of the runners sub list)!
Python code not fetching up to date sensor values
So I am trying to fetch for light sensor values using the light sensor that is part of GrovePi. When I run the sample script here (https://github.com/DexterInd/GrovePi/blob/master/Software/Python/grove_light_sensor.py) the code works perfectly so this leads me to conclude that the script I wrote is somehow only fetching for one value and just stores it and outputs it without fetching for the new updated value. Note: I am storing my values in a dictionary and posting to Dweet.io If anyone can lead me to the right direction that would be great, my code is below : import time import grovepi light_sensor = 0 grovepi.pinMode(light_sensor,"INPUT") def getLight(): sensor_value = grovepi.analogRead(light_sensor) s = sensor_value #S seems to print just one number here? print(s) return s def values(): dict = {} dict["light"] = getLight() return dict while True: dict = values() print (dweepy.dweetfor(n, dict)) time.sleep(2)
Not an engineer, but why are you adding the whole dictionary part at all? Your sample code does not do that, and dweet certainly does not need it. My guess is that is your issue, remove it. While True: print (dweepy.dweetfor(s))
Using an IF THEN loop with nested JSON files in Python
I am currently writing a program which uses the ComapaniesHouse API to return a json file containing information about a certain company. I am able to retrieve the data easily using the following commands: r = requests.get('https://api.companieshouse.gov.uk/company/COMPANY-NO/filing-history', auth=('API-KEY', '')) data = r.json() With that information I can do an awful lot, however I've ran into a problem which I was hoping you guys could possible help me with. What I aim to do is go through every nested entry in the json file and check if the value of certain keys matches certain criteria, if the values of 2 keys match a certain criteria then other code is executed. One of the keys is the date of an entry, and I would like to ignore results that are older than a certain date, I have attempted to do this with the following: date_threshold = datetime.date.today() - datetime.timedelta(days=30)`` for each in data["items"]: date = ['date'] type = ['type'] if date < date_threshold and type is "RM01": print("wwwwww") In case it isn't clear, what I'm attempting to do (albeit very badly) is assign each of the entries to a variable, which then gets tested against certain criteria. Although this doesn't work, python spits out a variable mismatch error: TypeError: unorderable types: list() < datetime.date() Which makes me think the date is being stored as a string, and so I can't compare it to the datetime value set earlier, but when I check the API documentation (https://developer.companieshouse.gov.uk/api/docs/company/company_number/filing-history/filingHistoryItem-resource.html), it says clearly that the 'date' entry is returned as a date type. What am I doing wrong, its very clear that I'm extremely new to python given what I presume is the atrocity of my code, but in my head it seems to make at least a little sense. In case none of this clear, I basically want to go through all the entries in the json file, and the if the date and type match a certain description, then other code can be executed (in this case I have just used random text). Any help is greatly appreciated! Let me know if you need anything cleared up. :) EDIT After tweaking my code to the below: for each in data["items"]: date = each['date'] type = each['type'] if date is '2016-09-15' and type is "RM01": print("wwwwww") The code executes without any errors, but the words aren't printed, even though I know there is an entry in the json file with that exact date, and that exact type, any thoughts? SOLUTION: Thanks to everyone for helping me out, I had made a couple of very basic errors, the code that works as expected is below:: for each in data["items"]: date = each['date'] typevariable = each['type'] if date == '2016-09-15' and typevariable == "RM01": print("wwwwww") This prints the word "wwwwww" 3 times, which is correct seeing as there are 3 entries in the JSON that fulfil those criteria.
You need to first convert your date variable to a datetime type using datetime.strptime() You are comparing a list type variable date with datetime type variable date_threshold.
Parsing JSON in Python (Reverse dictionary search)
I'm using Python and "requests" to practice the use of API. I've had success with basic requests and parsing, but having difficulty with list comprehension for a more complex project. I requested from a server and got a dictionary. From there, I used: participant_search = (match1_request['participantIdentities']) To convert the values of the participantIdentities key to get the following data: [{'player': {'summonerName': 'Crescent Bladex', 'matchHistoryUri': '/v1/stats/player_history/NA1/226413119', 'summonerId': 63523774, 'profileIcon': 870}, 'participantId': 1}, My goal here is to combine the summonerId and participantId to one list. Which is easy normally, but the order of ParticipantIdentities is randomized. So the player I want information on will sometimes be 1st on the list, and other times third. So I can't use the var = list[0] like how I would normally do. I have access to summonerId, so I'm thinking I can search the list the summonerId, then somehow collect all the information around it. For instance, if I knew 63523774 then I could find the key for it. From here, is it possible to find the parent list of the key? Any guidance would be appreciated. Edit (Clarification): Here's the data I'm working with: http://pastebin.com/spHk8VP0 At line 1691 is where participant the nested dictionary 'participantIdentities' is. From here, there are 10 dictionaries. These 10 dictionaries include two nested dictionaries, "player" and "participantId". My goal is to search these 10 dictionaries for the one dictionary that has the summonerId. The summonerId is something I already know before I make this request to the server. So I'm looking for some sort of "search" method, that goes beyond "true/false". A search method that, if a value is found within an object, the entire dictionary (key:value) is given.
Not sure if I properly understood you, but would this work? for i in range(len(match1_request['participantIdentities'])): if(match1_request['participantIdentities'][i]['summonerid'] == '63523774': # do whatever you want with it. i becomes the index you're searching for.
ds = match1_request['participantIdentities'] result_ = [d for d in ds if d["player"]["summonerId"] == 12345] result = result_[0] if result_ else {} See if it works for you.
You can use a dict comprehension to build a dict wich uses summonerIds as keys: players_list = response['participantIdentities'] {p['player']['summonerId']: p['participantId'] for p in players_list}
I think what you are asking for is: "How do I get the stats for a given a summoner?" You'll need a mapping of participantId to summonerId. For example, would it be helpful to know this? summoner[1] = 63523774 summoner[2] = 44610089 ... If so, then: # This is probably what you are asking for: summoner = {ident['participantId']: ident['player']['summonerId'] for ident in match1_request['participantIdentities']} # Then you can do this: summoner_stats = {summoner[p['participantId']]: p['stats'] for p in match1_request['participants']} # And to lookup a particular summoner's stats: print summoner_stats[44610089] (ref: raw data you pasted)