How to create dictionary from lists

1

How to associate lists with keys and values to create a dictionary in Python?

Is the problem the following? I have a large csv file and I need to read the first line (make it into a list) that should be used to bind to the Keys and the following lines should be the values.

One option I imagined would be to use for loops to read each item in the lists and do the assignment. But do not you have a function / method that does this?

Here is a snippet of the code, considering only the keys and the first line (values).

The next step is to build a list of dictionaries, each for each line; but I think I know how to do it.

f = open("beatles-diskography.csv", "r")

hd = f.readline()
fl = f.readline()
hd = hd.split(',')
fl = fl.split(',')

c = 0
for s in hd:
    s = s.strip()
    hd[c] = s
    c = c+1

c = 0
for s in fl:
    s = s.strip()
    fl[c] = s
    c = c+1

'''
dic = ???
'''
    
asked by anonymous 12.05.2018 / 17:50

1 answer

3

One possibility is you use the DictReader class. of the module csv , which maps information to a OrderedDict (dictionary that maintains the order of entry).

Example:

import csv

# Abre o arquivo
with open("beatles-diskography.csv", "r") as f:
    # Lê os dados do csv no formato OrderedDict
    rd = csv.DictReader(f)
    for linha in rd:
        # Exemplo de acesso aos dados
        print("{0} - {1} - {2}".format(linha['Title'], linha['Released'], linha['Label']))

Example output:

Please Please Me - 22 March 1963 - Parlophone(UK)
With the Beatles - 22 November 1963 - Parlophone(UK)
Beatlemania! With the Beatles - 25 November 1963 - Capitol(CAN)
Introducing... The Beatles - 10 January 1964 - Vee-Jay(US)
Meet the Beatles! - 20 January 1964 - Capitol(US)
Twist and Shout - 3 February 1964 - Capitol(CAN)
The Beatles' Second Album - 10 April 1964 - Capitol(US)
The Beatles' Long Tall Sally - 11 May 1964 - Capitol(CAN)
...
    
12.05.2018 / 18:34