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

4 Answers 4

3

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']}
Sign up to request clarification or add additional context in comments.

1 Comment

I am learning the list and dictionary comprehension, so i was trying to code first in old way. Thank you for highlighting to the reset value.
0

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

1 Comment

Thank you for answering the question
0
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']}

Comments

-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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.