0
list1=[1,2,3,4]
list2=['a','b','c','d']

Now i need to convert them into a dictionary by

final_list = dict(zip(list1,list2))

I need to add values:

1:a,m,o
2:b,y,z
..
3
  • 1
    Where does the m, o, y, z come from. Are these meant to be lists in the dictionary, or strings? Commented Nov 28, 2017 at 3:56
  • strings......... Commented Nov 28, 2017 at 4:29
  • It is still unclear where the other characters come from. Commented Nov 28, 2017 at 6:31

2 Answers 2

1

It sounds like you want to add multiple values to a single key in a dictionary. Either assign the value of the key an array or another dictionary. Here is how you could assign it an array

list1=[1,2,3,4]
list2=['a','b','c','d']

final_list = dict(zip(list1,list2))

final_list[1] = ['x', 'y', 'z']

print final_list[1]

final_list[1].append('aa')

print final_list[1]

This can also be simply created and modified from scratch, without the unnecessary steps in the beginning

final_list = {1: ['x', 'y', 'z'], 2: 'b', 3: 'c', 4: 'd'}

print final_list[1]

final_list[1].append('aa')

print final_list
Sign up to request clarification or add additional context in comments.

4 Comments

how can you add values into this??
edited to demonstrate appending to this list. also added code showing how to do this starting fresh
final_list[1] = ['x', 'y', 'z'] all time i have to initialise it to an array then only in can append it.. ?
You have to initialize your dictionary and set the value of one of the keys, to a list. In the example I provided (the edited one) the first line initializes the dictionary, sets the key '1' in the dictionary to have a value of a list (['x', 'y', 'z']). Now that the value is a list, we can use standard list functions
0

You can concatentate to the strings contained in d. There are a few ways, the easiest is to use the += operator:

list1=[1,2,3,4]
list2=['a','b','c','d']
d = dict(zip(list1,list2))

d[1] += ',m,o'
d[2] += ',y,z'
...

Following this dictionary d will be:

{1: 'a,m,o', 2: 'b,y,z', ...}

2 Comments

we have to add not contactinate
@Pam: what is the difference?

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.