0

I am using a program that spits result in format [(11,3.22),(12,4.6),(9,2.4)] I need to extract the first part to change it to names and attach the second value and store this in a csv file. How do I extract each part of subpart?

1
  • What names do you mean? Commented Nov 26, 2013 at 1:18

2 Answers 2

1
>>> l = [(11,3.22),(12,4.6),(9,2.4)]

"need to extract the first part" -

>>> l[0]
(11, 3.22)

"change it to names" -

>>> l[0] = ('x', 'y')
>>> l
[('x', 'y'), (12, 4.6), (9, 2.4)]

"attach the second value" -

>>> l[0] = dict(zip(('x', 'y'), l[1]))
>>> l
[{'y': 4.6, 'x': 12}, (12, 4.6), (9, 2.4)]

Storing in CSV is easy, check an example here - http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/

Sign up to request clarification or add additional context in comments.

Comments

0

I am assuming that you mean for each tuple in the list, replace the first element with a string that's mapped from the integer.

You can use list comprehensions to do so:

>>> id_to_str_map = {11:"foo", 12:"bar", 9:"baz"}
>>> l = [(11,3.22),(12,4.6),(9,2.4)]
>>> result = [(id_to_str_map[idx], value) for (idx, value) in l]
>>> print result
[('foo', 3.22), ('bar', 4.6), ('baz', 2.4)]

Using the CSV standard library module as recommended by @theharshest is the most robust option. Standard library documentation for Python 2.7: http://docs.python.org/2/library/csv.html

If you're working with a large dataset, then it's likely better to instead use a generator expression to lazily perform the mapping as you are writing out each row to the csv file.

import csv
id_to_str_map = {11:"foo", 12:"bar", 9:"baz"}
l = [(11,3.22),(12,4.6),(9,2.4)]
with open("blah.csv", "wb") as csvfile:
    csv_writer = csv.writer(csvfile)
    for row in ((d[idx], value) for (idx, value) in l):
        csv_writer.writerow(row)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.