0

For example, if

list1=[1,2,3]
list2=[[1,1,1],[2,2,2],[3,3,3]]

I'd like to create a dictionary like

dict1={'1':[1,1,1],'2':[2,2,2],'3':[3,3,3]}

How can I realize it through loops? I tried

dict1=dict().fromkeys(list1)
for i in range(len(list1)):
    dict1['i']=list2[i]

But I failed, so is there anyone can help me deal with this problem? One more question, if I firstly create an empty dataframe, df1

df1=pd.DataFrame()

and I hope use the elements in list1 as columns' name of df1. How can I realize it?

Thanks for your assistance!

1
  • dict(zip(map(str, list1),list2)) Commented Dec 9, 2016 at 2:28

3 Answers 3

1

You can use zip() with dict() to convert the two lists to a dictionary:

dict(zip(list1, list2))
# {1: [1, 1, 1], 2: [2, 2, 2], 3: [3, 3, 3]}

To construct a data frame with list1 as columns:

pd.DataFrame(dict(zip(list1, list2)))

#   1   2   3
#0  1   2   3
#1  1   2   3
#2  1   2   3
Sign up to request clarification or add additional context in comments.

Comments

0

You failed if you tried to use

dict1['i']

instead of

dict1[i]

Since you are only using the letter/string i as the key whilst you have keys generated from the list i.e. ['1','2','3']

If you are starting off you should look at coding it up like this then move to move pythonic ways.

dict1 = {}
for i, key in enumerate(map(str,list1)):
     if key not in dict1:
          dict1[key] = list2[i]

This will get you thinking about dictionaries.

Comments

0

You can just append the items into the dictionary if you want to use loops.

d = {}
l = [1,2,3,4,5]
for i in range(len(l)): 
    d[i] = l[i] 

When you print d you will have {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}

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.