Yoav Poni
Yoav Poni

Reputation: 85

Unpacking list values to a text

I a list, that I want to unpack to a part of text. The goal is eventually exporting the text to a txt file and then to use VPN to implement it to our database.

The text is this:

'"name": "----"',

'"lei": " "',

'"parentId": "0"',

'"status": "ACTIVE"',

'"type": "1"',

'"country": "----"',

'"region": "1"',

'"address": "----"',

'"domains": "None"'

It started from a DataFrame that I turned into a list, so basically each value in each of the lists is correlated to the same one with the same index in the other lists.

The goal is to have 318 texts like the one I wrote that each text will have the 3 values.

The lists are - "Name", "Country", "Address"

I thought of using map with a for loop but I'm not so sure how to make that happen.

Any suggestions?

Upvotes: 1

Views: 86

Answers (2)

Archeo
Archeo

Reputation: 221

I think you could use python's string formatting to achieve what you are trying to do, and, as you suggested, use map to perform the task on all your files.

The idea is to write a generic text, like the one you presented, replacing the "----" fields by "{0}", "{1}", "{2}" fields. Then, applying text.format(name, country, adress) will fill the fields, in that order, with the contents of the name, country and adress fields.

To map it, you will also want to unpack a tuple containing the arguments, using the splat operator (*) : text.format(*tuple_of_arguments).

Thus, an acceptable solution is to use a code of the following form:

list_of_tuples = [
        ('nameA', 'countryA', 'adressA'),
        ('nameB', 'countryB', 'adressB')
    ] # fill this, and maybe use a generator instead (e.g. using zip)
for e in map(lambda x : text.format(*x), list_of_tuples):
    # do what you want of the formatted text stored in e

I hope this helps !

Upvotes: 1

Błotosmętek
Błotosmętek

Reputation: 12927

format_string = """
'"name": "{}"',
'"lei": " "',
'"parentId": "0"',
'"status": "ACTIVE"',
'"type": "1"',
'"country": "{}"',
'"region": "1"',
'"address": "{}"',
'"domains": "None"'
"""

for data in zip(Name, Country, Address):
    print(format_string.format(*data))

Is this what you wanted?

Upvotes: 1

Related Questions