How to create dictionary from lists

Asked

Viewed 641 times

1

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

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

An option I imagined would be to use loops for to read each list item and do the assignment. But there is a function / method that does this?

Follows an excerpt of the code, considering only the header (Keys) and the first line (values).

The next step will be to put together a list of dictionaries, each for each line; but this I think I know how to do.

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 = ???
'''

1 answer

3


One possibility is to use the class Dictreader module csv, that maps information to a guy Ordereddict (dictionary that maintains the input order).

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)
...
  • 1

    Elegant code! + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.