I think it's pretty simple what I want to do, but I'm struggling a little bit because of fundamentals I don't have.
What I want to do is look for a certain string on a JSON file and then, after I find it, take the next string on list instead of the one I found.
The code I'm using right now is this:
jsonarquivos = open(nomejson, 'r')
data = json.load(jsonarquivos)
for sub_dict in data:
if imageid in data:
Now I don't know what to put on the if.
EDIT
There is a little example of how the JSON looks like:
["lccw2w", "lcdrqx", "lck63p", "lck9d3"]
so If I'm looking for the imageid = "lcdrqx", I want "lck63p" to come out instead.
Use list.index() to determine its index in the list, then access the next item in the list:
with open(nomejson, 'r') as jsonarquivos:
data = json.load(jsonarquivos)
for sub_dict in data:
if imageid in data:
i = data.index(imageid)
if i + 1 < len(data):
print(f'next image is {data[i+1]}')
else:
print(f'{imageid} is the last item')
What this code does it gets the values of a json.loads file. It gives me a list of dictionary that are organized by dates. This code works, my understanding is, i am taking the the first value in the list of dictionaries, so the first dictionary, but shouldn't. self.get_jsonparsed_data(self.ticker_text.get().upper())[0] work as well? In my case it doesn't, I was hoping if someone can explain why I does not work.
def get_jsonparsed_data(self, ticker):
#quote
url = (f"https://financialmodelingprep.com/api/v3/quote/{ticker}?)
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
def search_info(self):
#self.info.delete(0, END)
recent_filing = []
for header in self.get_jsonparsed_data(self.ticker_text.get().upper())[:1]:
recent_filing.append(header)
ticker = self.ticker_text.get()
#output dictionary values with proper format
try:
recent_filing_dict = recent_filing[0]
This works.
I get the first dictionary which is what i want but when i do self.get_jsonparsed_data(self.ticker_text.get().upper())[0] instead of self.get_jsonparsed_data(self.ticker_text.get().upper())[:1] it gives me an error
which pretty much is saying there isnt any values appended to recent_filing_dict. I was just hoping if someone can explain why?
"for" loops through iterable and self.get_jsonparsed_data(self.ticker_text.get().upper())[0] seemingly returns an item rather than iterable (list) while self.get_jsonparsed_data(self.ticker_text.get().upper())[:1] returns an iterable (single item list) which is iterated over by for loop
I'm trying to extract data from a JSON file with Python.
Mainly, I want to pull out the date and time from the "Technicals" section, to put that in one column of a dataframe, as well as pulling the "AKG" number and putting that in the 2nd col of the dataframe. Yes, I've looked at similar questions, but this issue is different. Thanks for your help.
A downNdirty example of the JSON file is below:
{ 'Meta Data': { '1: etc'
'2: etc'},
'Technicals': { '2017-05-04 12:00': { 'AKG': '64.8645'},
'2017-05-04 12:30': { 'AKG': '65.7834'},
'2017-05-04 13:00': { 'AKG': '63.2348'}}}
As you can see, and what's stumping me, is while the date stays the same the time advances. 'AKG' never changes, but the number does. Some of the relevant code I've been using is below. I can extract the date and time, but I can't seem to reach the AKG numbers. Note, I don't need the "AKG", just the number.
I'll mention: I'm creating a DataFrame because this will be easier to work with when creating plots with the data...right? I'm open to an array of lists et al, or anything easier, if that will ultimately help me with the plots.
akg_time = []
akg_akg = []
technicals = akg_data['Technicals'] #akg_data is the entire json file
for item in technicals: #this works
akg_time.append(item)
for item in technicals: #this not so much
symbol = item.get('AKG')
akg_akg.append(symbol)
pp.pprint(akg_akg)
error: 'str' object has no attribute 'get'
You've almost got it. You don't even need the second loop. You can append the akg value in the first one itself:
for key in technicals: # renaming to key because that is a clearer name
akg_time.append(key)
akg_akg.append(technicals[key]['AKG'])
Your error is because you believe item (or key) is a dict. It is not. It is just a string, one of the keys of the technicals dictionary, so you'd actually need to use symbols = technicals[key].get('AKG').
Although Coldspeed answer is right: when you have a dictionary you loop through keys and values like this:
Python 3
for key,value in technicals.items():
akg_time.append(key)
akg_akg.append(value["akg"])
Python 2
for key,value in technicals.iteritems():
akg_time.append(key)
akg_akg.append(value["akg"])
I'm stuck right now and could really use some help, i've exhausted every resource google could find for me and I still can't figure out how to do what I am attempting. (If its even possible)
In my python program I am using Tkinter in Python 3.5.1 to make a little calculator applet. For the calculator in question I created a CSV file and imported it using csv.DictReader.
import csv
exptable = csv.DictReader(open('C:/Users/SampleInfo.csv'))
result = {}
for column in exptable:
key = column.pop('Current Level')
if key in result:
pass
result[key] = column
Now the part that I simply can't figure out is how to use the information contained WITHIN this imported dictionary. Here is what I am trying so far...
DropDownLevelVar = StringVar()
DropDownLevel = ttk.OptionMenu(root, {column})
DropDownLevel.grid(column=3, row=1)
This is leaving me with...
Error on line 49, in module DropDownLevel = ttk.OptionMenu(root, {column})
TypeError: unhashable type: 'dict'
The CSV Dictionary I am trying to use contains 2 columns of data, "Current Level and Total EXP" See This for what the Data looks like.
What I would like is for the OptionMenu Dropdown list to be populated with the values listed under Current Level within the dictionary.
My goal is to create a super simple calculator that calculates how many of a certain monster I would need to kill to reach my desired level. (If Current level = 55, then 100 Kills at 500xp ea until 56.) I imported the dictionary so that I could reference the values over and over if I needed to.
I'm REALLY new to programming so i'm sorry if I look like a complete idiot!
Why not use this method to populate your dict?
Anyway, to correctly populate the result dict:
import csv
exptable = csv.DictReader(open('C:/Users/SampleInfo.csv'))
result = {}
for column in exptable: # should actually be called `row`
key = column['Current Level']
if key not in result:
result[key] = column['Total EXP']
The for and if block can be better written as:
for column in exptable: # should actually be called `row`
if column['Current Level'] not in result:
result[column['Current Level']] = column['Total EXP']
If ttk.OptionMenu wants a dict, then the line DropDownLevel = ttk.OptionMenu(root, {column}) should probably be:
DropDownLevel = ttk.OptionMenu(root, result)
Edit: And the pythonic way to do this, as per the method linked above:
import csv
result = {}
with open('C:/Users/SampleInfo.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if row['Current Level'] not in result: # is this check necessary?
result[row['Current Level']] = row['Total EXP']
I have a list like this:
my_array= ["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
What I want to do is:
define('device','xyz')
define('asd','10')
define('pdf','6')
define('dsa','1')
define('pqa','2')
define('dga','12')
The way I approached is:
i=0
while i < len(my_array):
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
elif my_array[i][0]=="+":
print("'",my_array[i][1],"'","'",my_array[i][3],"'")
if my_array[i][4]=="\D":
print("'",my_array[i][4],"'","'",my_array[i][6],"'")
elif my_array[i][7]=="\D":
print("'",my_array[i][7],"'","'",my_array[i][9],"'")
i=i+1
But doing this, I get index error. I know where the problem is, but I cannot fix it with my very bad programming brain. Can someone help me on this?
First review problem seems in
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
because last element in your my_array is ['*'] and it has no other elements and u are trying to access my_array['*'][1] and its give index error.
You have to remove that element or add members who fulfill element index requirement.
Hard-coding the indices is a sure sign you're doing something wrong - the items in my_array have variable lengths, so some of your indices inevitably fail. I think what you want is something like:
for command in my_array:
if command[0] in ("*", "+"):
for start in range(1, len(command), 3):
assignment = command[start:start+3]
if assignment[1] in ("=", ":"):
print assignment[0], assignment[2]
It is worth noting, however, that you seem to be attempting to write a file parser. Although this code solves this specific problem, it is likely that your overall approach could be improved.
With the assumption, that every key in your list has a value attached to it(e.g. there are no two asterisk following after each other) you can make some simplifications:
We'll read the first value as a key of a new dict and the second item as the value.
With the newly tidied up dict(d) you can continue to work easily e.g. in a for loop:
array=["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
d = {}
for list in array:
new_key = None
for item in list:
if item in ['*',':','+','=']: continue
if new_key == None:
new_key = item
else:
d[new_key] = item
new_key = None
for key in d:
define(key,d[key])