Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying append a 'gameID' to a list if the game has been finished. I have a list of dictionaries called 'games_2020' that looks like
(ex. [ {'seasonYear': '2020', 'league': 'standard', 'gameID': '8133', 'statusGame': 'Finished', 'vTeam': LA}, {'seasonYear': '2020', 'league': 'standard', 'gameID': '8134', 'statusGame': 'Finished', 'vTeam': LA}.....]
My current code is below. 'gameID_finished' is where I want the 'gameID' for finished games to end up. games_2020 is what I want to iterate through. I am then trying to map through the entire list but I am running into an output of all the same 'gameID'
def check_finish(games):
if games_2020['statusGame'] == 'Finished':
gameID_finished.append(games_2020['gameID'])
else:
print('Scheduled')
You need to traverse each item in list to append to output. Please try the below code.
gameID_finished = []
games = [ {'seasonYear': '2020', 'league': 'standard', 'gameID': '8133', 'statusGame': 'Finished', 'vTeam': 'LA'}, {'seasonYear': '2020', 'league': 'standard', 'gameID': '8134', 'statusGame': 'Finished', 'vTeam': 'LA'}]
for games_2020 in games:
if games_2020['statusGame'] == 'Finished':
gameID_finished.append(games_2020['gameID'])
else:
print('Scheduled')
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 months ago.
Improve this question
How to convert the following Input to the desired output using python.
Input:
{'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
Output:
{'Id': 34, 'user': 'a.t#gmail.com', 'createdOn':'12 Oct', 'status': False, 'message': 'Hello'}
Just take first index for each value :
your_dict = {'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
your_dict = {key:val[0] for key, val in your_dict.items()}
Why are the values in a tuple to begin with?
old_dict = {'Id': (34,), 'user': ('a.t#gmail.com',), 'createdOn': ('12 Oct',), 'status': (False,), 'message': ('Hello',)}
new_dict = {k:v[0] for k,v in old_dict.items()}
print(new_dict)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
This is a similar problem posted here lots of time but I am unable to get my head around it.
import json
str2 ="""[{'cta': [], 'ctr': 2880509, 'client_id': '229132', 'exchange': 'NSE_EQ', 'token': '3063', 'product': 'CO', 'order_type': 'M', 'duration': 'DAY', 'price': '0', 'trigger_price': '149.10', 'quantity': 1, 'disclosed_quantity': 0, 'side': 'S', 'avg_price': '148.10', 'traded_quantity': 1, 'pending_quantity': 0, 'message': '', 'exchange_order_id': '1300000006005800', 'syom_order_id': 'NA', 'order_number': '191101000336718', 'timestamp': '01/11/2019,12:19:45', 'exchange_timestamp': '01-Nov-2019 12:19:45', 'status': 'complete', 'time_in_micro': '1572590985928000', 'is_amo': False, 'order_complexity': 'CO', 'request_id': '1', 'valid_date': '--', 'tag': 'JWEB|TB1', 'comments': 'PLACE ORDER :: 229132|NSE_EQ|3063|EQ|I|0|1|S|CO|WEB|IP-172-31-4-125|1572590985897', 'fill_id': '', 'original_message': '', '_amo': False}]"""
str2 = (json.dumps(str2))
print(str2)
print(str2['client_id'])
Why this doesn't work? It says -
print(str2['client_id'])
TypeError: string indices must be integers
Note that str2 is output from someplace and my goal is to fetch the client_id or any other variable.
So what I am seeking is what is the possible way to parse it?
There are mutliple problems here. You don't seem to be thinking this through.
You start with a string. Calling json.dumps on a string just gives you another string. But you couldn't have called json.loads on the original string either, because it is not JSON; it appears to be a string representation of a Python object.
But then, even if you had correctly parsed it, it still wouldn't work, because it represents a list of dictionaries, not a single dict.
It seems unlikely that this is actually the output from your external system. If you want further help, you will need to explain exactly how you got that string.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am creating a dictionary for a JSON file, through the use of a for loop.
However my for loop overwrites the entries
second_dict={}
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
I am getting this output
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'chess', 'age': 13},
'sara': {'hobbies': 'chess', 'age': 13}}
Instead of getting this one
{'suzen': {'hobbies': 'chess', 'age': 13},
'lilly': {'hobbies': 'reading', 'age': 14},
'sara': {'hobbies': 'dancing', 'age': 15}}
can anyone please point out my mistake?
thank you
new_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
x = zip(name, hobbies, age)
for n,h,a in x:
new_dict[n]={'hobbies': h, 'age': a}
print(new_dict)
third_dict={}
name=['suzen','lilly','sara']
hobbies=['chess','reading','dancing']
age=[13,14,15]
for i in range(len(name)):
second_dict={}
second_dict["hobbies"]=hobbies[i]
second_dict["age"]=age[i]
third_dict[name[i]]=second_dict
print(third_dict)
As pointed in comments, you should create a new object for each second_dict, there are 3 second_dict.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am trying to build an array from the information comming from a local json file.
The desired output array format is:
output = [
'elementa-element2-element3',
'elementa-element2-element3',
]
The input from json is:
import json
with open('/Users/user/test.json', 'r') as f:
array = json.load(f)
print (array)
{'responseHeader': {'zkConnected': True, 'status': 0, 'QTime': 2, 'params': {'q': 'facet_gender:man', 'start': '0', 'fq': 'lang:de', 'rows': '10000', 'wt': 'json', 'facet': 'true'}}, 'response': {'numFound': 1005, 'start': 0, 'docs': [
{'rmc': 'm228238-0042', 'title': 'Day-Date 40', 'family': 'Day-Date', 'familyCode': 'day-date', 'facet_case_title': ['Oyster, 40 mm, Gelbgold']},
{'rmc': 'm326935-0007', 'title': 'Sky-Dweller', 'family': 'Sky-Dweller', 'familyCode': 'sky-dweller', 'facet_case_title': ['Oyster, 42 mm, Everose-Gold']}, ...
How can I acess the rows and build my array from all rows?
output = array
while i < len(array)
output[i] = array['response']['docs'][i]['familyCode']+'/'+array['response']['docs'][i]['rmc']
The json.load() will return a dictionary. This dictionary can be nested, if the json file contains nested elements. This is the case in your example, too.
If you format your json a little bit, it will be more clear:
{
'responseHeader': {
'zkConnected': True,
'status': 0,
'QTime': 2,
'params': {
'q': 'facet_gender:man',
'start': '0',
'fq': 'lang:de',
'rows': '10000',
'wt': 'json',
'facet':
'true'
}
},
'response': {
'numFound': 1005,
'start': 0,
'docs': [
{'rmc': 'm228238-0042', 'title': 'Day-Date 40', 'family': 'Day-Date', 'familyCode': 'day-date', 'facet_case_title': ['Oyster, 40 mm, Gelbgold']},
{'rmc': 'm326935-0007', 'title': 'Sky-Dweller', 'family': 'Sky-Dweller', 'familyCode': 'sky-dweller', 'facet_case_title': ['Oyster, 42 mm, Everose-Gold']},
...
]
}
}
If you want to retrieve the "docs", you actually need this:
array["response"]["docs"]
In your example, it is a list, and it can be used as you would normally do.
Example 1: get the first element of the list
documents = array["response"]["docs"] # Create new variable "documents".
print(documents[0]) # Print out first element of "docs" variable.
Example 2: Iterate over every element:
documents = array["response"]["docs"]
for document in documents:
print(document)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm creating a dictionary from the college scorecard API, but I'm having trouble joining integer queries to my dictionary (ie. "2015.student.size"). How would I do that in my code? I've tried "str() for f in", but that doesn't seem to work.
This is what I've written in Python so far:
import requests
import json
def main():
url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json'
payload = {
'api_key': "api_key_here",
'_fields': ','.join([
'school.name',
'school.school_url',
'school.city',
'school.state',
'school.zip',
]),
'school.operating': '1',
'2015.academics.program_available.assoc_or_bachelors': 'true',
'2015.student.size__range': '1..',
'school.degrees_awarded.predominant__range': '1..3',
'school.degrees_awarded.highest__range': '2..4',
'id': '240444',
}
data = requests.get(url, params=payload).json()
for result in data['results']:
print(','.join(result.values()))
main()
What happens when I run the program:
vagrant#vagrant:/vagrant/scripts$ python test.py
Madison,www.wisc.edu,University of Wisconsin-Madison,WI,53706-1380
When I add "print data":
{u'results': [{u'school.city': u'Madison', u'school.school_url': u'ww
w.wisc.edu', u'school.name': u'University of Wisconsin-Madison', u'sc
hool.state': u'WI', u'school.zip': u'53706-1380'}], u'metadata': {u'p
er_page': 20, u'total': 1, u'page': 0}}
I think you are making this more difficult than necessary. Instead of the for loop, you can do
print(data)
Or if you want each dictionary from the list to be on its own line, instead of
print(','.join(result.values()))
Just do
print(result)