JSON Python Lists - python

I have got this json file
[{"url": ["instrumentos-musicales-126030594.htm", "liquidacion-muebles-y-electrodomesticos-127660457.htm"], "title": ["INSTRUMENTOS MUSICALES", "LIQUIDACION, MUEBLES Y ELECTRODOMESTICOS"]}]
mydata = json.load(json_data)
And then I'd like to manipulate mydata to append url-title pair to a list paginas
What would be a good solution in Python? I want to be able to have something like
paginas[0].url
instrumentos-musicales-126030594.htm
paginas[0].title
"INSTRUMENTOS MUSICALES"
paginas[1].url
"liquidacion-muebles-y-electrodomesticos-127660457.htm"
paginas[1].title
"LIQUIDACION, MUEBLES Y ELECTRODOMESTICOS"

paginas = mydata[0]
paginas["url"].append(new_url)
paginas["title"].append(new_title)
You still need to use json.dump to save it, of course.

If you want to extract the values to a new list:
new_list =[mydata[0]["url"],mydata[0]["title"]]
will give you:
[['instrumentos-musicales-126030594.htm', 'liquidacion-muebles-y-electrodomesticos-127660457.htm'], ['INSTRUMENTOS MUSICALES', 'LIQUIDACION, MUEBLES Y ELECTRODOMESTICOS']]
To access elements you can using indexing:
`mydata[0]["url"][0]` will give you "instrumentos-musicales-126030594.htm"
mydata[0]["title"][0] will give you "INSTRUMENTOS MUSICALES" etc..
You don't need to do anything to your data structure.

Related

How do I access both the typing from the API call?

So my current code looks like this:
response = requests.get("https://pokeapi.co/api/v2/pokemon/palkia").json()
data = response["types"][1]
print(data)
Write now it only give the dictionary of the second typing, how can I get the just the name of the to typing's as the result
response["types"] is a list of dictionaries, and by indexing it with [1] you access the second element. To get the names for all elements in response["types"], you could e.g. do
data = [e["type"]["name"] for e in response["types"]]

Convert a dictionary to accessible array in Python

How can I convert the following dictionary which contains an array within an array: to an array easily so I can access for example array[0]
{'New Beton': [`'C:\\User\\New map\\Test1.jpg',`'C:\\User\\New map\\Test2.jpg', 'C:\\User\\New map\\Test3.jpg']}
Which I need to convert to
New Beton = ["C:\\User\\New map\\Test1.jpg", "C:\\User\\New map\\Test2.jpg", "C:\\User\\New map\\Test3.jpg"]
Just access it directly.
you_dict['New Beton'][0]
And make sure your variable names don't have whitespace. I think except 'Rockstar' no language allows that.
Do you want to convert dictionary into a nested list? Then, something like this will work.
def convert(d):
l = []
for k, v in d.items():
l.append(v)
return l
d = {'foo':['bar', 'baz']}
l = convert(d)
print(l[0])
but there are better ways to get that value without creating a list. it'd ve great if you could share more details about what you want to do so that i can give you specific examples.

Manipulating a list of dictionaries

I successfully imported from the web this json file, which looks like:
[{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"},
etc ...
I want to extract the values of the key moid_au, later compare moid_au with the key values of h_mag.
This works: print(data[1]['moid_au']), but if I try to ask all the elements of the list it won't, I tried: print(data[:]['moid_au']).
I tried iterators and a lambda function but still has not work yet, mostly because I'm new in data manipulation. It works when I have one dictionary, not with a list of dictionaries.
Thanks in advance for other tips. Some links were confusing.
Sounds like you are using lambda wrong because you need map as well:
c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
list(map(lambda rec: rec.get('moid_au'), c))
['0.035', '0.028']
Each lambda grabs a record from your list and you map your function to that.
Using print(data[:]['moid_au']) equals to print(data['moid_au']), and you can see that it won't work, as data has no key named 'moid_au'.
Try working with a loop:
for item in data:
print(item['moid_au'])
using your approach to iterate over the whole array to get all the instances of a key,this method might work for you
a = [data[i]['moid_au']for i in range(len(data))]
print(a)
In which exact way do you want to compare them?
Would it be useful getting the values in a way like this?
list_of_dicts = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"}, {"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
mod_au_values = [d["moid_au"] for d in list_of_dicts]
h_mag_values = [d["h_mag"] for d in list_of_dicts]
for key, value in my_list.items ():
print key
print value
for value in my_list.values ():
print value
for key in my_list.keys():
print key

How to append/extend multiple elements into an Array?

I'm having issues trying to input headers into my array, I cannot append the array with headers of the values within the array. I've also attempted to use .extend, but it's also giving me issues.
mylist = []
for i in jsonResponse['M']:
if i['x'] == 'n':
x = ((i['x']))
y = ((i['x']['y']))
z = ((i['x']['z']))
mylist.append([x,y,z])
import pandas as pd
#panda related stuff
df0 = pd.DataFrame(data=mylist)
df0.to_excel(writer, sheet_name='Sheet1', header=True, index=False)
I'm trying to have:
mylist.append('Header1': [x],['Header2': [y],['Header3': [z])
I've tried using the .extend as I would think it's the most appropriate, but it's giving me error.
The purpose of this is when I write the data to excel, it would be most ideal to have a header. The problem stems from opening the array from the very beginning above the JSON pull, I think i have to open the array, because it's a means to allocate memory to store the values.
I was thinking as a solution would be to create an array for value from the JSON pull meaning:
x = []
y = []
z = []
for i in jsonResponse['M']:
if i['x'] == 'n':
x = ((i['x']))
y = ((i['x']['y']))
z = ((i['x']['z']))
x.append('header1':[x])
y.append('header2':[y])
z.append('header3':[z])
But I don't know if that's going to work; I really don't want to go through that as it's a bit labor intensive, because I have a lot of json objects.
I'm new to Python and never wrote anything in a language before. I'm trying, I've spent most my time copying script from the documentation and other users attempting to parse together a workable code and at the same time trying to understand what i'm trying to do.
What you're looking for is called a dictionary (or dict) in Python.
A dict allows you to create mappings like this:
{'name': 'John', 'age': 30}
So, now all you have to do is you need to create a dict inside your for loop and then append that dict to mylist.
for i in jsonResponse['M']:
...
mylist.append({'Header1': x, 'Header2': y, 'Header3': z})

Trying to iterate over a JSON object

I am trying to iterate over a JSON object, using simplejson.
def main(arg1):
response = urllib2.urlopen("http://search.twitter.com/search.json?q=" + arg1) #+ "&rpp=100&page=15")
twitsearch = simplejson.load(response)
twitsearch = twitsearch['results']
twitsearch = twitsearch['text']
print twitsearch
I am passing a list of values to search for in Twitter, like "I'm", "Think", etc.
The problem is that there are multiple text fields, one each for every Tweet. I want to iterate over the entire JSON object, pulling out the "text" field.
How would I do this? I'm reading the documentation and can't see exactly where it talks about this.
EDIT: It appears to be stored as a list of JSON objects.
Trying to do this:
for x in twitsearch:
x['text']
How would I store x['text'] in a list? Append?
Note that
twitsearch['results']
is a Python list. You can iterate over that list, storing the text component of each of those objects in your own list. A list comprehension would be a good thing to use here.
text_list = [x['text'] for x in twitsearch['results']]
Easy. Figured it out.
tweets = []
for x in twitsearch:
tweets.append(x['text'])

Categories