Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dictionary when conditions are met [Python]

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]]}

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading