string indices must be integers json - python

i have a json data https://steamcommunity.com/id/RednelssGames/inventory/json/730/2
need get names of all the items
r = requests.get('https://steamcommunity.com/id/RednelssGames/inventory/json/730/2')
if r.json()['success'] == True:
for rows in r.json()['rgDescriptions']:
print(rows['market_hash_name'])
getting error string indices must be integers

Change the for-loop as follows:
for rows in r.json()['rgDescriptions'].values():
print(rows['market_hash_name'])
By iterating over a dictionary like you did, you get the keys and not the values (rows). If you want to iterate over the values, you have to iterate over the return value of dict.values().

From the link you provided:
"rgDescriptions":{"4291220570_302028390":
rgDescriptions doesn't return an array, but an object (a dictionary, in this case) (notice the opening curly brace ({) rather than a regular square brace ([)).
By using for rows in r.json()['rgDescriptions']: you end up iterating over the dictionary's keys. The first key of the dictionary seems to be "4291220570_302028390", which is a string.
so when you do print(rows['market_hash_name']), you're attempting to access the 'market_hash_name' "index" of your rows object, but rows is actually a string, so it doesn't work.

Related

Python - get elements from list

From a python function, I get the following output:
['(0.412169, mississippi)']
The type indicates that it is a list. I want to extract the values from the list and save it as separate elements. I tried various functions to convert list to tuple, list to str, extracting the element by Index from the tuple or str, nothing worked out. When I try to extract the element by index, I either get '(' for the first element index 0, or when I try to extract through a iterator function, I get all the values split up like the full data set as a string.
How do I get values separately.
You can iterate over your data, remove the parentheses using slicing and split the string by comma to create a list, which will be appended to your output payload:
data = ['(0.412169, mississippi)', '(0.412180, NY)']
extracted_values = []
for d in data:
extracted_values += d[1:-1].split(",")
print(extracted_values)
# output: ['0.412169', ' mississippi', '0.412180', ' NY']
Your list content a string, not a list.
If you want to extract the content of a string, use the "eval" statement
my_tuple = eval("(0.412169, 'mississippi')")
Note that the "eval" function can be dangerous, because if your string content python code, it could be executed.

Pymongo find using $in with a list

The folowing expression works fine, returning the values that match the values list:
[...].find({"FieldName":{"$in":["Value1", "Value2", "Value3"]}})
But i have the list of values in a list object, like this:
valuesList = list()
valuesList.append("Value1")
valuesList.append("Value2")
valuesList.append("Value3")
But using the list object, a get no results:
[...].find({"FieldName":{"$in":[valuesList]}})
I Have also tried expanding the list in a formated string, like this:
strList = ', '.join(valuesList)
[...].find({"FieldName":{"$in":[strList]}})
but also, no results.
Note: If i force the list to have only one value, it works. Only when multiple values are suplied, the result is blank.
Any ideas on how to use "$in" in pymongo with a list of values in a list object?
I believe your problem is the fact that you have a list inside of a list.
Instead of:
[...].find({"FieldName":{"$in":[valuesList]}})
Try:
[...].find({"FieldName":{"$in":valuesList}})

Outputting None instead of Values

I am trying to utilize list comprehension to populate a new list, which is the length of text in a DataFrame column.
So if the text is "electrical engineer", it should output 19 etc. Instead, it just fills the list with None values
I have written out list comprehension below
all_text_length = [all_text_length.append(len(i)) for i in data['all_text']]
Expecting output of integer but its None
As a workaround, I am currently using (successfully)
[all_text_length.append(len(i)) for i in data['all_text']]```
Read the documentation on append: it works in-place. There is no returned value. What you've written is essentially
all_text_length = [None for i in data['all_text']]
It appears that you're trying to make a list comprehension to entirely change your list. Try this:
all_text_length = [len(i) for i in data['all_text']]
If you just need the lengths in a convenient form, would it do to form a new column? Simply apply len to the df column.
The value before the "for" statement in the list comprehension, will be added to the list. If you place a statement in there, like
all_text_length.append(len(i)
, the return value of that function will be added. Because .append() doesnt have areturn-statement in it, you get the value None as return type, wich will be added to your list.
Use the code #Prune recommended and it should work as you want.
You are trying to append to the same list on which you are doing list comprehension. Since the append returns a None type, you are getting None. The below code should work,
all_text_length = map(len, data['all_text'])
map is a function that takes another function (first argument) and applies it to every element in an iterable (second argument) and returns a list of the results.

ast.literal_eval - loop over string elements in a list

Goal: I want to extract longlat tuples in the map key from a request.POST below.
<QueryDict: {'map': ['(38.70053557156445, 149.81571853160858)', '(38.70060091643143, 149.8153966665268)'], 'csrfmiddlewaretoken': ###}>
Problem: I used ast.literal_eval to extract the tuples but somehow only 2nd tuple is returned.
markers = request.POST
position = ast.literal_eval(markers['map'])
I also tried looping over map with but this is giving me SyntaxError: unexpected EOF while parsing on tuple parentheses.
for idx, val in enumerate(markers['map']):
position = ast.literal_eval(markers['map'][idx])
Finally, I tried list(map(ast.literal_eval, markers['map'])), but this returns the same SyntaxError as above.
It’s common for query strings to be used to represent both keys with single values and keys with multiple values, so Django’s QueryDict requires that you specify the type you’re looking for:
position = list(map(ast.literal_eval, markers.getlist('map')))

What does this anonymmous split function do?

narcoticsCrimeTuples = narcoticsCrimes.map(lambda x:(x.split(",")[0], x))
I have a CSV I am trying to parse by splitting on commas and the first entry in each array of strings is the primary key.
I would like to get the key on a separate line (or just separate) from the value when calling narcoticsCrimeTuples.first()[1]
My current understanding is 'split x by commas, take the first part of each split [0], and return that as the new x', but I'm pretty sure that middle part is not right because the number inside the [] can be anything and returns the same result.
Your variable is named "narcoticsCrimeTuples", so you seem to be expected to get a "tuple".
Your two values of the tuple are the first column of the CSV x.split(",")[0] and the entire line x.
I would like to get the key on a separate line
Not really clear why you want that...
(or just separate) from the value when calling narcoticsCrimeTuples.first()[1]
Well, when you call .first(), you get the entire tuple. [0] is the first column, and [1] would be the corresponding line of the CSV, which also contains the [0] value.
If you narcoticsCrimes.flatMap(lambda x: x.split(",")), then all the values will be separated.
For example, in the word count example...
textFile.flatMap(lambda line: line.split()).map(lambda word: (word, 1))
Judging by the syntax seems like you are in PySpark. If that's true you're mapping over your RDD and for each row creating a (key, row) tuple, the key being the first element in a comma-separated list of items. Doing narcoticsCrimeTuples.first() will just give you the first record.
See an example here:
https://gist.github.com/amirziai/5db698ea613c6857d72e9ce6189c1193

Categories

Resources