6

I need to change my output from number 1 = 0 to (1:0) or ('1':0). I want to change to key value pair. Below is the code I'm using.

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print 'number ', number, ' = ', val

output: number 1 = 0 desired output is: ('1':0) or (1:0)

2
  • You can use dict(zip(numberlist,val_list)) if you want a dictionary.
    – Farhan.K
    Commented Mar 10, 2016 at 16:31
  • i want a dictionary to use Commented Mar 10, 2016 at 16:33

4 Answers 4

8
numberlist = [1, 2, 3]
val_list = [4, 5, 6]

mydictionary = dict(zip(numberlist,val_list))

This will create a dictionary with numberlistas the key and val_list as the value.

>>> mydictionary
{1: 4, 2: 5, 3: 6}
>>> mydictionary[1]
4
2

You can use a formatted print statement to achieve this:

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print "(%d:%d)" % (number, val, )

to print (1:0), or

numberlist = [1]
val_list = [0]
for (number, val) in zip(numberlist, val_list):
    print "('%d':%d)" % (number, val, )

to print ('1':0)

0

Personally, I'm a fan of the splat operator.

numberlist = [1, 3, 5]
val_list = [0, 2, 4]
for fmt in zip(numberlist, val_list):
    print("('{}':{})".format(*fmt))

Keep in mind that each item in each list is an integer, but is being printed with quotes. If you actually want to convert each to a string, you can do something like:

newList = zip(map(str, numberlist), val_list) # List of tuples
# or, if you want a dict:
newDict = dict(newList) # dict where each key is in numberlist and values are in val_list
0

Use the built in dict function after zip. This will give you a dictionary and then you can iterate over the dictionary to obtain a key value pair.

numberlist = [1]
val_list = [0]    
print dict(zip(numberlist, val_list))
1
  • This appears to use Python 2 syntax
    – Ilya
    Commented Aug 23, 2022 at 20:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.