I am trying to read data from an excel sheet and form a dictionary in a loop as below.
for row in range(2,sheet.max_row+1):
temp_list.clear()
for col in range (2,sheet.max_column):
temp_list.append(sheet.cell(row,col).value)
dict_key = sheet.cell(row,1).value
Create a dictionary
MyDataDictionary.update( {dict_key : temp_list})
Assuming my excel have two rows of data I am reading, my dictionary value always gets overwritten with the value from second row always
(Create a dictionary) if this is part of your code what i think is your dictionary is getting created each time you run the loop therefore you should create dictionary before running loop and then update it
Try something like this below:
if MyDataDictionary.get(dict_key, []):
#updates the existing key assuming that temp_list is always a list
MyDataDictionary.get(dict_key).extend(temp_list)
else:
#creates a new key
MyDataDictionary.update({dict_key : temp_list})
Related
I loaded the .npy file on colab using f=np.load(path/to/file)
The structure of data looks like this
When I try to see the keys of dictionaries in it, it displays
The keys in the files
Now I want to extract the rows based upon the values against key named "feature_path" as displayed in the image.
Upon using the function to retrieve the values against key="feature_path"
**myDict = {}
for d in f:
c = d['feature_path']
myDict[c] = myDict.get(c,0)+1
print(myDict)
feature = myDict.values()
frequency = myDict.keys()
print(feature)
print(frequency)**
if i just extract the values against this specific key it gives me an error
As my first dictionary didn't have that "Key" so I had to skip first row
I resolved it by editing
for d in f[1:]:
I have code that is opening a file and reading a dictionary that is inside a dictionary. I want to take all the values from the key "time" and all the values from the key "close" and join them together as a key:value pair in a separate dictionary. My code achieves this however, I need the resulting dictionary to be ordered the same way it was from the dictionary i'm pulling from since they are dates. For some reason after the 3rd iteration the dates begin to get scrambled inside the new dictionary i've created. Any way to fix this?
Here's the sample
import json
import datetime
dict={}
def parsehistory():
file = json.load(open('histoday.json')) #open file
for i in range(len(file["Data"])): #iterate through subdictionaries
time = file["Data"][i]["time"] #get all values from key "time"
close = file["Data"][i]["close"] #get all values from key "close"
convert = datetime.datetime.utcfromtimestamp(time).strftime('%m-%d-%Y') #convert time from unix to UTC
dict[convert] = close #join values
print(dict)
Here is a sample of the output which is clearly not ordered by date like which it came {'02-05-2018': 6937.08, '02-03-2018': 9251.27, '02-06-2018': 7701.25, '02-21-2018': 10481.66,}
Any help is appreciated
python dictionnaries are not ordered by default. You can create an OrderedDict if you want to remember the order of insertions.
Just replace your initialization of dict with:
dict = collections.OrderedDict()
The dictionnary will however be ordered by insertion order, not by date.
I have a Dictionary and I wish to save it into a csv file. However, using the code below, the value (ei. All the data in the key are put in one cell all together). However, I required for each value to be in a different column within the same row of the key it belongs to.
csvPatientListFinal = csv.writer(open('PatientListFinal.csv','wb'))
for key, value in PatientList.items():
csvPatientListFinal.writerow([key, value])
I have tried however I have been unsuccessful in my efforts.
Thank you
Update 1:
Sorry about the typo, however the code worked (it was written in the script without typos), but it was not the desired output. The Dictionary created by my script has 14 keys, and 721 items inside each key. They are a database of case subjects. An example of the Dictionary is the following: I use the "|" so represent the lines between each cell, my mistake. The data in the dictionary look like this:
PatientList = {'code' : ['1','2','3','4','5',6], 'name' : ['aho','awd','faw','fas','gas','gdas','fasw'] , 'surnames' : ['awds','fhtt','hfr','hyk','uyr','rtyd'], 'ID' : ['123','345','654','234','645','354'], 'description' : ['a long text','a long text','a long text','a long text','a long text','a long text'] }.
The csv table format should be ("|" is the space between each cell in a row)
(headers)A|B|C
(row 1)1|A|caro
(row 2)2|B|al
But the input that I had was
(headers in one cell) A,B,C
(row 1 in one cell) 1 A caro
(row 2 in one cell) 2 B al
All under the same column, that correspond to the key they belong. This is an image representation of the desired output:
I am now trying the following code:
csvPatientListFinal = csv.writer(open('PatientListFinal.csv','wb'))
for header in PatienList.keys():
csvPatientListFinal.writerow(izip[header, value for value in PatientList[header]])
However, it indicates, an Error of Invalid syntax in the area of "value for value". I am trying to figure out why.
Is there a better way to achieve my desired output? Is there something wrong with the code (apart from the syntax error which I currently can't guess why it is there)?
Thank you for the help
You can do it like this. Iterate over the length of the value lists (assuming they're all the same length as the one in code) with nested iteration over the keys.
with open('PatientListFinal.csv', 'w') as fp:
csvPatientListFinal = csv.writer(fp)
csvPatientListFinal.writerow(PatientList.keys())
for i in range(len(PatientList['code'])):
csvPatientListFinal.writerow([j[i] for j in PatientList.values()])
You might want to consider using an OrderedDict if order is important to you. There's currently no guarantee that the columns will be stored in the same order as they was entered.
I want to excel file like in above image, with more than 100 columns,
row_header = ['Student_id', 'Student_name', 'Collage_name', 'From', 'To',
.........upto 100 column name]
My Simple Question is how write flexible code, So if order of name change then, I don't have to write code again.
For first row which contains the only column name only I write following code. This will create the first row.
for item in row_header:
worksheet.write(row, col, item)
worksheet.set_row(row, col)
col += 1
Now problem I that, I am getting the list of dictionary, each dictionary contains the one student details, means each dictionary contains 100 key value.
student_list=
[{collage_name: IIIT-A, Student_name:'Rakesh','Student_id':1,.....up to 100 key},
{collage_name: IIIT-G, Student_name: 'Shyam', 'Student_id':2, ........ up to 100 key}]
As you can see that key order is not matching with the column's name order. If I try to write like above it will take 100 line of code. So I am looking for solution where we can assign the cell value according to column value. How to use xlsxWrite through key -value dictionary, so that require to write less number of code..
I have a webpage where I display a list of passenger information as a table. This is the usual stuff: arrival_time, flight number etc.
I've made the table editable so when the user clicks a certain column with information he can edit this column. When he finally clicks confirm I send only the columns that were edited along with value and row number to the view which is suppose to locate the row of the list from the data I sent, find the key and update the original value.
The json values I get from editing a column look like this:
[{u'classname': u'flight', u'column': 6, u'value': u'F1521', u'row': 0}, {u'classname': u'flight', u'column': 6, u'value': u'FI521', u'row': 1}]
The code I have so far to update the value looks like this:
# Original data
query = UploadOrderModel.objects.filter(hashId = receiptNr)
# Gives me a list of dictionaries containing these keys
data = query.values("office", "reserv", "title","surname","firstN",
"arrival", "flight", "transferF", "hotelD", "tour")
# Update
json_dump = json.loads(request.body)
if json_dump:
for d in json_dump:
# get row number
row = int(d['row'])
# updates dictionary value at row
data[row][d['classname']] = d['value']
But this does not update the value. I have checked if is getting the correct values to update and it is, so that's not the case, row is correct and if I print out:
data[row][d['classname']]
I get the element I want to update. Is there anything really obvious I'm missing here.
Should I be making updates to the entire row instead? so update the entire dictionary at
the current location?
EDIT:
I'm still having problems. First off, i misread your good answer lyschoening. I thought you meant that values() does not return a writeable list, silly me. The saving of the model is done later in the code and works as expected. However I still have the problem of the dictionary at the location I'm trying to update does not update at all :/
Ok I found out what was the problem.
django values() does not return a list of dictionaries as it looks but a ValuesQuerySet.
It is therefor not possible to do updates on this list as one would do with a regular list.
All I had to do was turning it into a list of dictionaries:
updates = [item for item in data]