Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip key value pairs in python

Tags:

python

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)

like image 698
Testerflorida Avatar asked Mar 10 '16 16:03

Testerflorida


People also ask

What does zip (*) do in Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

How do I find a key-value pair in Python?

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

Does zip create a dictionary?

You can create a dictionary with list of zipped keys and values. Using zip() function you can loop through multiple lists at once.

Can I zip more than two lists Python?

The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments. What is this? Here you have learned how to zip three (or more) lists in Python, using the built-in zip() function!


1 Answers

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
like image 134
Farhan.K Avatar answered Oct 08 '22 02:10

Farhan.K