I am trying to implement a customized automata where the transition table looks like:
The table is dynamic i.e. the column heading, row name, and data at every cell can be determined at run time. The column name and row name are also necessary.
I tried this code
table = []
table.append(["A",[0,["B",2],["C1",2]],[1,["C1",1]]])
table.append(["B",[0,["C",1]],[1,["C2",1]]])
table.append(["C",[0,["C1",1]],[1,["C2",1]]])
but I am unable to access the individual item in the cell i.e. B or 2 from B:2 etc. Then I tried
row = ["A","B","C","C1","C2"]
col = [0,1]
table = []
table.append([[["B",2],["C1",2]],["C1",1]])
table.append([["C",1],["C2",1]])
table.append([["C1",1],["C2",1]])
print(table[0][0][0][0])
Now, I can access the individual item (B in the above case) but I am lost with the four subscript. Specially, when I do not know the depth of the list in advance. Need to get some help to do it in some easy way. Being a novice, I will appreciate some explanation to the pythonic code.
Update: This is Non-deterministic Finite Automata. I tried the automaton package but they are not solving my problem. Following the solution of Tadhg-Mcdonald-Jensen, it give the correct out put for the first row (A) in the table but an error message for second row (B). Here is the code
table = {}
table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}}
table["B"] = {0: {"C":1}, 1: {"C2",1}}
table["C"] = {0: {"C1":1}, 1: {"C2",1}}
for key,value in table["A"][0].items(): \\ok treated as dictionary (1)
print(key, value, sep="\t")
for key,value in table["A"][1].items(): \\ok treated as dictionary (2)
print(key, value, sep="\t")
for key,value in table["B"][0].items(): \\ok treated as dictionary (3)
print(key, value, sep="\t")
for key,value in table["B"][1].items(): \\wrong: why treated as set? Although same as (2)
print(key, value, sep="\t") \\Error message: AttributeError: 'set' object has no attribute 'items'
The output is
B 2
C1 2
C1 1
C 1
Traceback (most recent call last):
File "C:/Users/Abrar/Google Drive/Tourism Project/Python Projects/nestedLists.py", line 17, in <module>
for key,value in table["B"][1].items():
AttributeError: 'set' object has no attribute 'items'
Pandas is great at doing tables but you could also move to dictionaries, either way, list is not the data structure you want.
table = {}
table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}}
table["B"] = {0: {"C":1}, 1: {"C2":1}}
table["C"] = {0: {"C1":1}, 1: {"C2":1}}
Then table["A"][0] will give you the first element, each element will have one or more entries, if you wanted to iterate over the entries you can do for key,value in table["A"][0].items()
Or to iterate over the entire table you could use 3 nested for loops:
#do_stuff = print
for row, line in table.items():
#each row in the table, row will go through ("A", "B", "C")
for column, cell in line.items():
#each cell in the row, column will go through (0, 1)
for label, value in cell.items():
#each entry in cell, most only have one entry except table["A"][0]
do_stuff(row, column, label, value)
To be honest I don't understand what the table represents so I can't give you specific advice but I think this would at least be a clearer data structure.
Related
I have 2 variables I am trying to manipulate the data. I have a variable with a list that has 2 items.
row = [['Toyyota', 'Cammry', '3000'], ['Foord', 'Muustang', '6000']]
And a dictionary that has submissions
submission = {
'extracted1_1': 'Toyota', 'extracted1_2': 'Camry', 'extracted1_3': '1000',
'extracted2_1': 'Ford', 'extracted2_2': 'Mustang', 'extracted2_3': '5000',
'reportDate': '2022-06-01T08:30', 'reportOwner': 'John Smith'}
extracted1_1 would match up with the first value in the first item from row. extracted1_2 would be the 2nd value in the 1st item, and extracted2_1 would be the 1st value in the 2nd item and so on. I'm trying to update row with the corresponding submission and having a hard time getting it to work properly.
Here's what I have currently:
iter_bit = iter((submission.values()))
for bit in row:
i = 0
for bits in bit:
bit[i] = next(iter_bit)
i += 1
While this somewhat works, i'm looking for a more efficient way to do this by looping through the submission rather than the row. Is there an easier or more efficient way by looping through the submission to overwrite the corresponding value in row?
Iterate through submission, and check if the key is in the format extractedX_Y. If it does, use those as the indexes into row and assign the value there.
import re
regex = re.compile(r'^extracted(\d+)_(\d+)$')
for key, value in submissions.items():
m = regex.search(key)
if m:
x = int(m.group(1))
y = int(m.group(2))
row[x-1][y-1] = value
It seems you are trying to convert the portion of the keys after "extracted" to indices into row. To do this, first slice out the portion you don't need (i.e. "extracted"), and then split what remains by _. Then, convert each of these strings to integers, and subtract 1 because in python indices are zero-based.
for key, value in submission.items():
# e.g. key = 'extracted1_1', value = 'Toyota'
if not key.startswith("extracted"):
continue
indices = [int(i) - 1 for i in key[9:].split("_")]
# e.g. indices = [0, 0]
# Set the value
row[indices[0]][indices[1]] = value
Now you have your modified row:
[['Toyota', 'Camry', '1000'], ['Ford', 'Mustang', '5000']]
No clue if its faster but its a 2-liner hahaha
for n, val in zip(range(len(row) * 3), submission.values()):
row[n//3][n%3] = val
that said, i would probably do something safer in a work environment, like parsing the key for its index.
I have a made a dictionary and tried to call out the value but I am getting value of the excel cell row number also along with the cell value. I only want the values of the respective cells. Here's what I am getting while I run the code. I have attached the images. And why does it show dtype: object. Am I missing something in the code? or something is wrongly written.
def Trainreadin(actfile, actsheetname):
frame = Input.xclReadIn(actfile, actsheetname)
dict = {'resistance':
[']resistance_name(word)_A(N)_B(N/(km/h))_C(N/(km/h)2)_windT(km/h)_windB(km/h)', 'table']
outputdict = {key: framehandle.value_readin(value) for (key, value) in dict.items()}
outputdict["resistance_A"] = outputdict["resistance"][1]
outputdict["resistance_B"] = outputdict["resistance"][2] * 3.6
print(outputdict["resistance_A"])
return outputdict
In the CSV I'm reading from, there are multiple rows for each ID:
ID,timestamp,name,text
444,2022-03-01T11:05:00.000Z,Amrita Patel,Hello
444,2022-03-01T11:06:00.000Z,Amrita Patel,Nice to meet you
555,2022-03-01T12:05:00.000Z,Zach Do,Good afternoon
555,2022-03-01T11:06:00.000Z,Zach Do,I like oranges
555,2022-03-01T11:07:00.000Z,Zach Do,definitely
I need to extract each such that I will have one file per ID, with the timestamp, name, and text in that file. For example, for ID 444, it will have 2 timestamps and 2 different texts in it, along with the name.
I'm able to get the text designated to the proper ID, using this code:
from collections import defaultdict
d = {}
l = []
list_of_lists = []
for k in csv_file:
l.append([k['ID'],k['text']])
list_of_lists.append(l)
for key, val in list_of_lists[0]:
d.setdefault(key, []).append(val)
The problem is that this isn't enough, I need to add in the other values to the one ID key. If I try:
l.append([k['ID'],[k['text'],k['name']]])
I get
ValueError: too many values to unpack
Just use a list for value instead,
{key: [value1, value2], ...}
I'm importing a CSV to a dictionary, where there are a number of houses labelled (I.E. 1A, 1B,...)
Rows are labelled containing some item such as 'coffee' and etc. In the table is data indicating how much of each item each house hold needs.
Excel screenshot
What I am trying to do it check the values of the key value pairs in the dictionary for anything that isn't blank (containing either 1 or 2), and then take the key value pair and the 'PRODUCT NUMBER' (from the csv) and append those into a new list.
I want to create a shopping list that will contain what item I need, with what quantity, to which household.
the column containing 'week' is not important for this
I import the CSV into python as a dictionary like this:
import csv
import pprint
from typing import List, Dict
input_file_1 = csv.DictReader(open("DATA CWK SHOPPING DATA WEEK 1 FILE B.xlsb.csv"))
table: List[Dict[str, int]] = [] #list
for row in input_file_1:
string_row: Dict[str, int] = {} #dictionary
for column in row:
string_row[column] = row[column]
table.append(string_row)
I found on 'geeksforgeeks' how to access the pair by its value. however when I try this in my dictionary, it only seems to be able to search for the last row.
# creating a new dictionary
my_dict ={"java":100, "python":112, "c":11}
# list out keys and values separately
key_list = list(my_dict.keys())
val_list = list(my_dict.values())
# print key with val 100
position = val_list.index(100)
print(key_list[position])
I also tried to do a for in range loop, but that didn't seem to work either:
for row in table:
if row["PRODUCT NUMBER"] == '1' and row["Week"] == '1':
for i in range(8):
if string_row.values() != ' ':
print(row[i])
Please, if I am unclear anywhere, please let me know and I will clear it up!!
Here is a loop I made that should do what you want.
values = list(table.values())
keys = list(table.keys())
new_table = {}
index = -1
for i in range(values.count("")):
index = values.index("", index +1)
new_table[keys[index]] = values[index]
If you want to remove those values from the original dict you can just add in
d.pop(keys[index]) into the loop
I am trying to compare two rows of data to one another which I have stored in a list.
for x in range(0, len_data_row):
if company_data[0][0][x] == company_data[1][0][x]:
print ('MATCH 1: {} - {}'.format(x, company_data[0][0][x]))
# do nothing
if company_data[0][0][x] == None and company_data[1][0][x] != None:
print ('MATCH 2: {} - {}'.format(x, company_data[1][0][x]))
# update first company_id with data from 2nd
if company_data[0][0][x] != None and company_data[1][0][x] == None:
print ('MATCH 3: {} - {}'.format(x, company_data[0][0][x]))
# update second company_id with data from 1st
Psuedocode of what I want to do:
If data at index[x] of a list is not None for row 2, but is blank for row 1, then write the value of row 2 at index[x] for row 1 data in my database.
The part I can't figure out is if in SQLAlchemy you can do specify which column is being updated by an "index" (I think in db-land index means something different than what I mean. What I mean is like a list index, e.g., list[1]). And also if you can dynamically specify which column is being updated by passing a variable to the update code? Here's what I'm looking to do (it doesn't work of course):
def some_name(column_by_index, column_value):
u = table_name.update().where(table_name.c.id==row_id).values(column_by_index=column_value)
db.execute(u)
Thank you!