Reputation: 109
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)
Upvotes: 6
Views: 17544
Reputation: 3626
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))
Upvotes: 0
Reputation: 4681
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
Upvotes: 0
Reputation: 3485
numberlist = [1, 2, 3]
val_list = [4, 5, 6]
mydictionary = dict(zip(numberlist,val_list))
This will create a dictionary with numberlist
as the key and val_list
as the value.
>>> mydictionary
{1: 4, 2: 5, 3: 6}
>>> mydictionary[1]
4
Upvotes: 8
Reputation: 1705
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)
Upvotes: 2