I have created some code to merge json documents (aka dictionaries) that I need to merge by looping through them and then adding them to a list of 'merged' json documents (myList).
So myList is a list of lists containing jsons!
Here is a snapshot of the code that is adding the 2 jsons. It took me a while to figure out a solution and only after I added the first line (it appears I have to initiate a new list), it worked. Otherwise I would get an 'out of index-range' error.
Is there a simpler way of doing this?
for ....
myList.append([])
myList[cnt].append(dict1)
myList[cnt].append(dict2)
cnt += 1
As mer mezba's comment. A much simpler way of doing this is
for ....
myList.append([ dict1, dict2 ])
cnt += 1
This will create a new list within mylist and add both json docs (as dictionaries). Adding to an existing list can still be done using e.g.
myList[someExistingIndex].append(dict1)
Related
I am writing the following code in Python, I want to accomplish the following using a for condition
if (datetime_obj.hour==7):
hour7.append(a)
if (datetime_obj.hour==8):
hour8.append(a)
if (datetime_obj.hour==9):
hour9.append(a)
if (datetime_obj.hour==10):
hour10.append(a)
if (datetime_obj.hour==11):
hour11.append(a)
if (datetime_obj.hour==12):
hour12.append(a)
if (datetime_obj.hour==13):
hour13.append(a)
if (datetime_obj.hour==14):
hour14.append(a)
if (datetime_obj.hour==15):
hour15.append(a)
hour are empty arrays.
Make hour a list of lists, e.g., hour = [[] for _ in range(24)], such that hour[7] would give you whatever you have for hour7, etc. Then you can simply do
hour[datetime_obj.hour].append(a)
No ifs or loops.
If the values that datetime_obj.hour takes aren't consecutive values from 0 to some number, then use a dictionary of lists instead.
It seems like your code will be greatly simplified by abandoning the specific references to each empty list (e.g. hour1, hour2). Rather, you should create some structure which holds the lists, and allows you to access them in a sensible way. The existing answer uses a nested list, which is a good option. Another way would be with a dict:
hours = {i:[] for i in range(24)}
hours[datetime_obj.hour].append(a)
hours is initialized as a dictionary where each key is an integer (representing an hour of the day) and each value is a separate empty list. You can select those empty lists by directly using datetime_obj.hour, and then append your a.
You can check out here for a relevant discussion; for both convenience and functionality, avoiding these repetitive sequential named variables is recommended!
I have received a json file from an api and want to convert it from to a dictionary to a list in python. I already have it loaded as a python dictionary, so I'm really just looking to iterate over it and convert from a dictionary to a list. However, the dictionary has nested lists and not every object within the json file's many objects is always structured the same (i.e. the api will not always return the same json object for every event). I want to convert the dictionary to 3 separate lists, each list for a specific key:value pair I am parsing for.
I've tried using KeyError in a try/except statement to account for cases where there is no value but haven't had much luck. Also tried importing defaultdict from collections to no success as well. I gather I should be able to make the rests of my lists once I get some help with this first one. Hopefully I didn't overcomplicate the question
data = load_json()# function responsible for loading the json from a stored file
new_list = []
for some_key1 in data
if new_list['some_key1'] > 0:
try:
new_list.append(['some_key1'], some_key1)
except:
new_list.get(['some_key1'], '0')
for x in range(len(new_list)):
print(new_list[x])
I am looking to make one list for storing each object's (i.e. each python 'breaking' dictionary) key:value pair where some_key1 exists (i.e. this means in this case I will have a list for aDifferentCherry and yetAnotherDifferentCherry.
I have a list that should contain all my other lists. Currently I append every list separately but that just looks pretty ugly..
looplist = [] # initiate an empty list that contains all date from the other lists
[...]
looplist.append(internallist1)
[...]
looplist.append(internallist10)
the internallists are all getting initialized and filled in a for loop
You can simply use + to merge them.
You may check for more info.
If you want to have list of lists, check this topic.
listOne.extend(anotherList)
this could help you: https://docs.python.org/3/tutorial/datastructures.html
you can also do listOne+=anotherList and this is less expensive, as it doesn`t involve a function call like extend
To answer what you are asking, Just initialize looplist with your 10 lists.
looplist = [internallist1,
internallist2,
internallist3] #Note: internallist3,] is also valid, python allows trailing comma. Nifty!
However, your 10 lists really shouldn't be separately named lists in the first place if this is your real use case. Just use looplist[0] through looplist[9] instead from the get go.
The zip method could work for you as you stated your output should:
look something like [ [list1], [list2], ... , [list n] ]
in your case the code would be similar to
looplist = list(zip(internallist1,[...], internallist10))
I'm relatively new to python and programing and have code that is working, however I'd like to know if there is a better more condensed way to achieve the same thing.
My code creates a dictionary with some context key value pairs, then I go and get groups of questions looping a number of times. I want to gather all the questions into my data dictionary, adding the list of questions the first time, and extending it with subsequent loops.
My working code:
data = {
'name': product_name,
'question summary': question_summary,
}
for l in loop:
<my code gets a list of new questions>
if 'questions' not in data:
data ['questions'] = new_questions['questions']
else:
all_questions = data.get('questions')
all_questions.extend(new_questions['questions'])
data ['questions'] = all_questions
I've read about using a default dict to enable automatic creation of a dictionary item if it doesn't exist, however I'm not sure how I would define data in the first place as some of its key value pairs aren't lists and I want it to have the extra context key value pairs.
I also feel that the 3 lines of code appending more questions to the list of questions in data (if it exists) should/could be shorter but this doesn't work as data.get() isn't callable
data['questions'] = data.get('questions').extend(new_questions['questions'])
and this doesn't work because extend returns none:
data['questions'] = all_questions.extend(new_questions['questions'])
Ok so I figured out how to condense the 3 lines, see answer, below however I'd still like to know if the If: else: is good form in this case.
You might be looking for the setdefault method:
data.setdefault('questions', []).extend(new_questions['questions'])
Ok so Quack Quack I figured out how to condense the 3 lines - this works:
data['questions'].extend(new_questions['questions'])
I am trying to edit values in dictionaries created by dictreader. If I understand this correctly, it creates a list of dictionaries. This part is working fine. However, I'd like to change some of the values for the key:value pairs in certain dictionaries and this is not functioning the way I expect. After I finish editing the values, my dictreader object seems to be completely empty.
To deal with this, I make an empty list (elis) and then fill it with all the dictionaries that were in the dictreader object.
My code follows:
import csv
import numpy as np
import pandas as pd
# Load the csv into a dictreader object
elistable = csv.DictReader(open("./elispotable.csv", 'rU'))
# This code will print all the dictionaries when uncommented
# for item in elis:
# print item
# Create an empty list
elis=[]
#Note that the dicts have keys including 'Control' and 'Peptide Id'
for item in elistable:
if item['Control']=='Neg':
item['Peptide Id']='Neg'
if item['Control']=='Pos':
item['Peptide Id']='Pos'
elis.append(item)
#Elis is now full with all the dictionaries and correct values that were edited in the for loop
dude=[]
for item in elistable:
dude.append(item)
print dude
Dude is totally empty and if I try to run a for loop to print the dicts from elistable, nothing prints. It works before I run the for loop with if statements, but not after. It seems to be completely empty now.
Is it possible to edit the values in the dictionaries created by the dictreader? Am I somehow overwriting them all?
If I understand this correctly, it creates a list of dictionaries.
It doesn't; a DictReader is an iterator that generates the next dictionary when you request it. As with all Python iterators (and as with regular file object iteration), if you try to iterate over it twice, the second loop will see the iterator as empty, since the iterator doesn't go back to the start after the first loop.
If you want a list, call list on it:
elistable = list(csv.DictReader(open("./elispotable.csv", 'rU')))
Separate loops will then use separate iterators over the list.