Mayank S
Mayank S

Reputation: 11

create dictionary with for loop (python)

cols = 'ABC'
ind = range(3)

value=[]

dic = {}

for c in cols:
        for i in ind:
            value.append(str(c) + str(i))
        dic[c] = value

print(dic) 

output:

{'A': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2'], 'B': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2'], 'C': ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']}

why am i getting the above output ?

while I want the output to be like

output:

{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}

Upvotes: 1

Views: 82

Answers (4)

yogesh ramesh
yogesh ramesh

Reputation: 1

def make_df(cols, ind):          
    # Create a DataFrame           
    data = {c: [str(c) + str(i) for i in ind] for c in cols}
    return pd.DataFrame(data, ind)

# Example DataFrame       
make_df('ABC', range(3))

Upvotes: -1

Ahmed Soliman
Ahmed Soliman

Reputation: 1710

cols = 'ABC'
dic = {c:[c + str(x) for x in range(3)] for c in cols}

print(dic) 

Output:

{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}

Upvotes: 0

Spark
Spark

Reputation: 2485

Thats simple you have to reset you array after each iteration

cols = 'ABC'
ind = range(3)
dic = {}
for c in cols:
    value=[]
    for i in ind:
        value.append(str(c) + str(i))
    dic[c] = value
print(dic) 

Result:

{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}

Upvotes: 0

Boseong Choi
Boseong Choi

Reputation: 2596

Because you used same object value for every values.
You should insert value = [] in the for c in cols: block,
But here is more pythonic way:

cols = 'ABC'
ind = range(3)

dic = {
    c: [c + str(i) for i in ind]
    for c in cols
}
print(dic)

output:

{'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2'], 'C': ['C0', 'C1', 'C2']}

Upvotes: 3

Related Questions