1

I have been trying to solve this problem but I cannot get it right :( I am querying mySQL database in Django, and my results comes back as a tuple inside of an array. Please see dummy data below;

query_results = [
    (500, datetime.date(2017, 1, 1)),
    (302, datetime.date(2017, 1, 2)),
    (550, datetime.date(2017, 1, 3)),
    (180, datetime.date(2017, 1, 4)),
    (645, datetime.date(2017, 1, 5)),
    (465, datetime.date(2017, 1,6))
]

500, 302, 550 etc... are my records. The next element are the date of those records. I would like to append them into a dictionary using a loop, but I always get an error of:

TypeError: list indices must be integers, not tuple.

Can anyone please give me some advise on how to append these into something like this:

myDict = {
    "record": "",
    "date": ""
}

All help is greatly appreciated!

6
  • ... foo = dict(query_results) ? Commented Aug 28, 2017 at 21:13
  • 1
    Do you want a list of dictionaries? Or a dictionary with the first element as key and the second as value? Commented Aug 28, 2017 at 21:14
  • I would like myDict = { "record": "302", "date": "somedate" } Commented Aug 28, 2017 at 21:15
  • and logs everything inside the dictionary Commented Aug 28, 2017 at 21:15
  • You might be using django wierly. How are you getting these results? Commented Aug 28, 2017 at 21:19

4 Answers 4

2

You could unpack the list of tuples and zip them into a dict with the keys you want,

dict(zip(['record', 'date'], zip(*query_results)))

which outputs

{'date': (datetime.date(2017, 1, 1),
          datetime.date(2017, 1, 2),
          datetime.date(2017, 1, 3),
          datetime.date(2017, 1, 4),
          datetime.date(2017, 1, 5),
          datetime.date(2017, 1, 6)),
 'record': (500, 302, 550, 180, 645, 465)}

Update

If you're hoping for a list of dicts, you could use a list comprehension directly.

[dict(record=record, date=date) for record, date in query_results]

which outputs

[{'date': datetime.date(2017, 1, 1), 'record': 500},
 {'date': datetime.date(2017, 1, 2), 'record': 302},
 {'date': datetime.date(2017, 1, 3), 'record': 550},
 {'date': datetime.date(2017, 1, 4), 'record': 180},
 {'date': datetime.date(2017, 1, 5), 'record': 645},
 {'date': datetime.date(2017, 1, 6), 'record': 465}]
Sign up to request clarification or add additional context in comments.

2 Comments

Hello, thank you very much! I was able to unpack the tuples. Is there a way I can achieve something like this : mydict = { "record": 500, "date": 2017, 1, 1 },{ "record": 302, "date": 2017, 1, 2 },{ "record": 550, "date": 2017, 1, 3 } I am trying to achieve this because I am passing this distionary in my javascript later on. thanks for your reply! Very mcuh appreciated
Thank you Mitch! This is what I needed. So much simple than I thought! :) thank again
0

This loop should do:

    my_dict = {}
    for item in query_results:
        my_dict[item[0]] = item[1]

This will stick your records (500, 550, etc.) as dictionary keys (item[0] part) so that you can easily call them out. And the value associated with those keys will be the datetime object (item[1] part).

If you want a more complicated solution please let us know.

Tom

3 Comments

Thank you very much tom! This is what I needed. I have been aiming for this. In my next step, how can I name the records records? like this.. mydict = { "record": 500, "date": 2017, 1, 1 },{ "record": 302, "date": 2017, 1, 2 },{ "record": 550, "date": 2017, 1, 3 } I think it will be easier to refer to this later on if I do this format.
@Marvin what do you mean by name the records? Record is a field in the dictionary. Do you mean to have a dictionary of dictionaries? Then you could have an identifier for each.
If you are using a dictionary each keyname must be unique and associating a new value to the existing key replaces the old value.
0

If you want them as a tuple inside the dictionary, Mitch's answer would work.

If you want a separate dictionary in each loop, you can do:

for result in query_results:
    myDict = {}
    myDict["record"] = result[0]
    myDict["date"] = result[1]
    your_operation()

Or if you want the record as the key, and the date as the value (unless you have repeating records, this could be very useful) you can do:

myDict = {}
for result in query_results:
    myDict[result[0]] = result[1]

Then you would have:

myDict = {"500": datetime.date(2017, 1, 1), 
          "302": datetime.date(2017, 1, 2), 
          etc..}

Comments

0

Alternative format to Mitch's answer, as the post was a bit ambiguous on wanted result:

>list_of_dicts = [ {'result': tup[0], 'date': tup[1]} for tup in query_results]

>list_of_dicts[0]    
{'result':500, 'date':datetime.date(2017, 1, 1) }

Building on other disucssion if you would rather have each record key to a date time you can instead build a dictionary of each record as an entry. This assumes that the records will never be duplicates. In which case the comprehension would look like this:

my_dict = {str(record) : date for record, date in query_results}

where the dict looks like:

{"500": date1, "501", date2} #but not necessarily in order

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.