Premise that i'm still looking for a solution. By extracting the values from a Sql, i create a dictionary in the following way.
As you can see the key is the set of row[0],row[1],row[2], row[3], row[4]
, while the value is only row[5].
PROBLEM: The problem is that I can access only the key and value (which is for example [0, 1, 1, 5]). I would like to access individual row[0],row[1],row[2], row[3], row[4] and row[5] separately.
How can I create a dictionary where for example:
- the key is New York-Dallas (so
row[0]
) - the values are NHL (then
row[1]
), 8.1 (thenrow[2]
), 9 (thenrow[3]
), 15.00 (thenrow[4]
) and finally [0, 1, 1, 5] (thenrow[5]
)
So something like {('New York-Dallas': 'NHL', 8.1, 9, '15:00', [0, 1, 1, 5]
P.S: I'm still looking for answers. I have been given a helpful answer, but I don't want to convert the dictionary leaving the bad code, but I want to edit the dictionary code directly
x={}
for row in next.fetchall():
x.setdefault((row[0],row[1],row[2], row[3], row[4]), []).append(row[5])
Output
#{('New York-Dallas', 'NHL', 8.1, 9, '15:00'): [0, 1, 1, 5],
#('Vegas-Chicago', 'NHL', 8.1, 9, '18:00'): [1, 2, 3, 4]}
CodePudding user response:
If I understood your question well, you want to transform the x
to have keys only from the first value of the tuples:
x={}
for row in next_.fetchall(): # <-- don't use `next`, that's built-in function
x.setdefault((row[0],row[1],row[2], row[3], row[4]), []).append(row[5])
# transform the x:
x = {a: [*rest, lst] for (a, *rest), lst in x.items()}
print(x)