List Dictionary Values

I am new to Python and I am trying to learn how to manipulate 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 to convert the key as follows

 '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 very slow and awkward. Is there any Pathonic way to achieve this?

Thank!

+4
source share
5 answers

This gives you exactly what you want:

d = { k : tuple(map(list, zip(*d[k]))) for k in d }

Conclusion:

{'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])}

Also, consider a different name than dict, since this is the name of an inline class dict.


zip(*d[k]) zip(d[k][0], d[k][1]), .

map(list, ...) , zip ( python2 )

tuple(...) map/generator , .

+1

:

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()}

:

{'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])}
+3

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

[[1990, 1.5], [1991, 1.6], [1992, 1.7], [1993, 1.8]]
+3

:

res = {k: zip(v[0], v[1]) for k, v in d.items()}

:

>>> {k: zip(v[0], v[1]) for k, v in d.items()}
{'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)]}
+1

, , - for key, (year, value).

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])} 

a = {k : [list(group) for group in zip(year, val)] for k, (year, val) in d.items()}

enter image description here

+1

Source: https://habr.com/ru/post/1680432/


All Articles