saptarshi ghosh
saptarshi ghosh

Reputation: 11

How to convert values in a dictionary into a comma separated string, also the dictionaries are present inside a list

My input data is given below:

l =  [{u'lat': 57.161597, u'lng': -1.0962736},
      {u'lat': 32.3794617, u'lng': -0.0834768}]

I want to convert it into the following list:

l_1 = [{57.161597, -1.0962736},
       {32.3794617, -0.0834768}]

Can I also get the output as:

l_1 = ['57.161597, -1.0962736', '32.3794617, -0.0834768']

Upvotes: 0

Views: 1411

Answers (4)

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

Here a try with list comprehension:

k = [{u'lat': 57.161597, u'lng': -1.0962736}, {u'lat': 32.3794617, u'lng': -0.08347689999999999}]
l = [set(i.values()) for i in k]
print(l)

If you want the O/P in list of list then you can do like this :

l = [list(i.values()) for i in k]

UPDATE :

If you want flat list of string elements you can do like this :

s = [','.join(map(str,i.values())) for i in k]

O/P :

['-1.0962736, 57.161597', '-0.08347689999999999, 32.3794617']

Upvotes: 1

Yon P
Yon P

Reputation: 206

Or something like this

>>>import re
>>>l_1 = re.sub(r"['lngat:]", "", str(l))
>>>print(l_1)
[{ -1.0962736,  57.161597}, { -0.0834768,  32.3794617}]

Upvotes: 0

Rahul K P
Rahul K P

Reputation: 16081

You can do like this,

In [12]: map(lambda x:set(x.values()),input_data)
Out[12]: [{-1.0962736, 57.161597}, {-0.08347689999999999, 32.3794617}]

As per your second suggestion for string.

In [21]: [','.join(map(str,i.values())) for i in input_data]
Out[21]: ['57.161597,-1.0962736', '32.3794617,-0.0834769']

OR

In [17]: map(lambda x:','.join(map(str,x.values())),input_data)
Out[17]: ['57.161597,-1.0962736', '32.3794617,-0.0834769']

Upvotes: 1

Sunitha
Sunitha

Reputation: 12015

>>> l = [{'lat': 57.161597, 'lng': -1.0962736}, {'lat': 32.3794617, 'lng': -0.08347689999999999}]
>>> [set(d.values()) for d in l]
[{57.161597, -1.0962736}, {32.3794617, -0.08347689999999999}]
>>> 

Upvotes: 1

Related Questions