Reputation: 189
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!
Upvotes: 4
Views: 1620
Reputation: 19806
One approach would be using this concise solution:
res = {k: zip(v[0], v[1]) for k, v in d.items()}
Output:
>>> {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)]}
Upvotes: 1
Reputation: 402263
This gives you exactly the output you want:
d = { k : tuple(map(list, zip(*d[k]))) for k in d }
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])}
Also, do consider a different name than dict
as this is the name of the built-in dict
class.
zip(*d[k])
is a simplified version of zip(d[k][0], d[k][1])
but they both do the same thing and generate pairwise tuples.
map(list, ...)
generates a map object that converts each element in the zip
to a list (in python2 tuples are automatically converted to lists)
tuple(...)
converts the map
list/generator to a tuple of lists, which is exactly what you want.
Upvotes: 2
Reputation: 71451
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])}
Upvotes: 3
Reputation: 3464
I'm just going to throw my answer in, because I haven't seen anyone take advantage of for key, (year, value)
yet. Which I find quite readable and direct
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()}
Upvotes: 1
Reputation: 1344
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]]
Upvotes: 3