Home > Software engineering >  Create a dictionary when conditions are met [Python]
Create a dictionary when conditions are met [Python]

Time:04-26

I have a dictionary, with name of file as keys and its values as the data I am working on. And at the moment, I am trying to create 3 new ones, depending on certain conditions. <\br> The condition I want to apply is that if the file is already in one of the previous dictionaries it should be ignored and not be added to the data dictionary file. <\br>

import pandas as pd
d1 = {'\\2%-sample-1-amp-fts.csv': pd.DataFrame([[1,3],[1,1]], columns = headers), 
  '\\-0%-sample-1-amp-fts.csv': pd.DataFrame([[1,0],[1,0]], columns = headers),
  '\\-100%-sample-1-amp-fts.csv':pd.DataFrame([[100,100],[100,100]],columns = headers),
  '\\20%--1-amp-fts.csv':pd.DataFrame([[1,3],[1,3]],columns = headers)}

t_100 = {}
t_0   = {}
data_ = {}
for k, v in d1.items():
    if '-100%-' in k:
        r = k.rfind('\\')
        a = k[r 1:-4]
        t_100[a] = v
    
    if '-0%-' in k:
        r = k.rfind('\\')
        a = k[r 1:-4]
        t_0[a] = v
    else:
        data_[k] = v

<\br>

OUTPUT DESIRED

data_ = {'2%-sample-1-amp-fts':[[1,3],[1,1]]), 
        '20%--1-amp-fts':[[1,3],[1,3]]}
t_100 = {'0%-sample-1-amp-fts': [[1,0],[1,0]]}
t_0   = {'100%-sample-1-amp-fts':[[100,100],[100,100]]}

CodePudding user response:

Maybe you should write your loop this way:

d1 = {'\\2%-sample-1-amp-fts.csv': pd.DataFrame([[1,3],[1,1]], columns = headers), 
  '\\-0%-sample-1-amp-fts.csv': pd.DataFrame([[1,0],[1,0]], columns = headers),
  '\\-100%-sample-1-amp-fts.csv':pd.DataFrame([[100,100],[100,100]],columns = headers),
  '\\20%--1-amp-fts.csv':pd.DataFrame([[1,3],[1,3]],columns = headers)}

t_100 = {}
t_0   = {}
data_ = {}
for k, v in d1.items():
    if '-100%-' in k:
        r = k.rfind('\\')
        a = k[r 1:-4]
        t_100[a] = v
        continue
    if '-0%-' in k:
        r = k.rfind('\\')
        a = k[r 1:-4]
        t_0[a] = v
        continue
    data_[k] = v
  • Related