[Tutor] Converting a sequence of dictionaries to a single dictionary
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Jun 22 03:30:08 EDT 2016
On 22/06/16 01:41, Ek Esawi wrote:
> I am trying to read a csv file via DictReader and produce a single
> dictionary without fieldnames; that is, I just want a single dictionary
> that contains tests as keys and grades as values as shown below in my
> sample file.
OK, As you've discovered that's not what the csv reeaders do.
They produce a data structure per line. Thats because CSV files
usually contain one discrete data record per line. If you want to pull
all the records into a single dictionary you will need to do that
yourself, probably using a standard tuple based reader.
> I want to create a single dictionary with only Tests and Grades; that’s
> {Test1:A,Test2:b,Test3:c etc.}. I tried several ways but nothing worked.
> File
> Test Grade
> Test1 A
> Test2 B
> Test3 C
So the reader will give you
[('Test1','A'),('Test2','B'),...]
So you need to take the list of tuples and put
them in a dict. Luckily that's exactly what the dict()
function does when given a list of tuples.
>>> dict([(1,2),(3,4)])
{1: 2, 3: 4}
>>>
So you just need to call dict() on your reader data.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list