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!
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]]
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])}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With