Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehensions of dictionary values

I am new to Python and I am trying to learn manipulating a dictionary. I have a dict that has the following structure:

dict = {'city1':([1990, 1991, 1992, 1993],[1.5,1.6,1.7,1.8]),
        'city2':([1993, 1995, 1997, 1999],[2.5,3.6,4.7,5.8])   

I would like convert the key of in the following way

 'city': ([1990, 1.5],[1991, 1.6],[1992,1.7],[1993,1.8])

I tried using a for loop to loop through the values and create a new value for each key. However, this seems really slow and clumsy. Is there any Pathonic way of achieving this goal?

Thanks!

like image 992
macintosh81 Avatar asked Dec 24 '22 16:12

macintosh81


2 Answers

You can try the following code

a = [[a, b] for a, b in zip(dict['city1'][0], dict['city1'][1])]

Output

[[1990, 1.5], [1991, 1.6], [1992, 1.7], [1993, 1.8]]
like image 157
Mr_U4913 Avatar answered Feb 06 '23 03:02

Mr_U4913


You can try this:

d = {'city1':([1990, 1991, 1992, 1993],[1.5,1.6,1.7,1.8]),
    'city2':([1993, 1995, 1997, 1999],[2.5,3.6,4.7,5.8])}   

new_dict = {a:tuple(map(list, zip(b[0], b[1]))) for a, b in d.items()}

Output:

{'city2': ([1993, 2.5], [1995, 3.6], [1997, 4.7], [1999, 5.8]), 'city1': ([1990, 1.5], [1991, 1.6], [1992, 1.7], [1993, 1.8])}
like image 23
Ajax1234 Avatar answered Feb 06 '23 02:02

Ajax1234