python help loop for to create dictionary

Viewed 79

Hi everyone I have such a data structure from CSV file. I would like to create a dictionary divided by place that contained the various dates referring to that day.

DATA        | LUOGO     | CAP       | KEY
05/05/12    LUOGO1       05254        545122
05/05/12    LUOGO2       05554        545745
05/05/12    LUOGO3       05444        555544
05/05/12    LUOGO4       05774        777888
05/05/12    LUOGO5       05854        542225

06/05/12    LUOGO1       05554        585547
06/05/12    LUOGO2       07854        545888
06/05/12    LUOGO3       04544        585858
06/05/12    LUOGO4       05778        789585
06/05/12    LUOGO5       05785        525477

I'd get something like that with a for loop, I've been banging my head on it for days but I can't find a solution that I guess is trivial

luoghi = { 'LUOGO1': 
                    {'05/05/12': {'data': '05/05/12', 'LUOGO': 'LUOGO1', 'CAP': '05254', 'KEY': '545122'},
                    '06/05/12': {'data': '06/05/12', 'LUOGO': 'LUOGO1', 'CAP': '05554', 'KEY': '585547'}},
           'LUOGO2': {'05/05/12': {'data': '05/05/12', 'LUOGO': 'LUOGO2', 'CAP': '05554', 'KEY': '545745'},
                      '06/05/12': {'data': '06/05/12', 'LUOGO': 'LUOGO2', 'CAP': '07854', 'KEY': '545888'}}
        }


print(luoghi['LUOGO1']['05/05/12'])

Result:

{'data': '05/05/12', 'LUOGO': 'LUOGO1', 'CAP': '05254', 'KEY': '545122'}

Can anyone tell me how with a FOR loop I can get it?

Thank you very much

5 Answers

here your code

luoghi = { 'LUOGO1': 
                    {'05/05/12': {'data': '05/05/12', 'LUOGO': 'LUOGO1', 'CAP': '05254', 'KEY': '545122'},
                    '06/05/12': {'data': '06/05/12', 'LUOGO': 'LUOGO1', 'CAP': '05554', 'KEY': '585547'}},
           'LUOGO2': {'05/05/12': {'data': '05/05/12', 'LUOGO': 'LUOGO2', 'CAP': '05554', 'KEY': '545745'},
                      '06/05/12': {'data': '06/05/12', 'LUOGO': 'LUOGO2', 'CAP': '07854', 'KEY': '545888'}}
        }


for  key,value in luoghi.items():
    for key2,value2 in value.items():
        print(value2)

if you need output as list type here is your another code

print([val2 for key,val in luoghi.items() for key2,val2 in val.items()])

Does something like that does the trick ?

import re

luoghi = {}
with open("test.csv", "r") as f:
    # Skip the first line
    f.readline()

    # Iterate on other lines
    for line in f:
        if line.strip() != "":
            data, luogo, cap, key = re.split("\s+", line.strip())

            # new luogo ?
            if not luogo in luoghi.keys():
                luoghi[luogo] = {}
            
            # new data for luogo ?
            if not data in luoghi[luogo].keys():
                luoghi[luogo][data] = {}

            # Push data
            luoghi[luogo][data] = {
                'data'  : data,
                'LUOGO' : luogo,
                'CAP'   : cap,
                'KEY'   : key
            }

With your data being saved in the test.csv file of course.

You can try this:

luoghi = {}
with open("path/to/luoghi.csv", "r") as csv_file:
    _ = csv_file.readline()  # first line is only the header, we don't care about
    for csv_line in csv_file.readlines():
        stripped_line = csv_line.strip()
        if not len(stripped_line):
            # in case of an empty line
            continue
        data, luogo, cap, key = [
            field for field in stripped_line.split(" ") if len(field)
        ]

        if luogo not in luoghi:
            luoghi[luogo] = {}

        luoghi[luogo][data] = {"data": data, "LUOGO": luogo, "CAP": cap, "KEY": key}

You can delete the empty line check if non-existence of empty lines are guaranteed in the csv.

I mis expressed myself. the structure I put in was just an example of the file. the CSV file is online and the code used to open it is as follows.

url = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv"
r = requests.get(url)
buff = io.StringIO(r.text)
filecsv = csv.DictReader(buff)

I would like to create a split dictionary called PLACES where for each region (Abruzzo, Basilicata etc.) corresponds a date (2020-02-24T18:00:00, 2020-02-25T18:00:00) and at each date the row corresponds with all the other data.

I would like you to then write

print(luoghi['Abruzzo']['2020-09-05T17:00:00'])

the result corresponds to

{'data': '2020-09-05T17:00:00', 'stato': 'ITA', 'codice_regione': '13', 'denominazione_regione': 'Abruzzo', 'lat': '42.35122196', 'long': '13.39843823', 'ricoverati_con_sintomi': '32', 'terapia_intensiva': '2', 'totale_ospedalizzati': '34', 'isolamento_domiciliare': '449', 'totale_positivi': '483', 'variazione_totale_positivi': '12', 'nuovi_positivi': '13', 'dimessi_guariti': '2910', 'deceduti': '472', 'casi_da_sospetto_diagnostico': '3396', 'casi_da_screening': '469', 'totale_casi': '3865', 'tamponi': 
'164140', 'casi_testati': '106544', 'note': 'Dal totale dei positivi è stato sottratto 1 caso precedentemente conteggiato 2 volte'}
import pandas as pd

data=pd.read_csv('data/Tect.csv')

data2=data.set_index(['LUOGO','DATA'])
key1=data['LUOGO'].unique()
key2= data['DATA'].unique()

data_dict=dict()
for k1 in key1:
    new_dict=dict()
    for k2 in key2:
        new_dict[k2]=list(data2.loc[k1,k2])
    data_dict[k1]=new_dict
data_dict['LUOGO1']['05/05/12']
Related