Skip to content
Advertisement

Create a dictionary using a foor-loop and add a label for each in python

I have the following data, however I want to create a dictionary using a foor loop.

data = [("TEXT 1", 'no'), ("TEXT 2", 'yes'), ("TEXT 3", 'no'), ("TEXT 4", 'no'), ("TEXT 5", 'yes')]

Is it possible to do that?

I need a dictionary with this structure:

[({"TEXT 1": 'no'}, "Comment 1"),
 ({"TEXT 2": 'yes'}, "Comment 2")]

Comment 1, Comment 2 and so on are arbitrary labels that I am assigning and are not mentioned in my dataset.

Advertisement

Answer

A simple way to write this down:

data = [
    ("TEXT 1", 'no'), ("TEXT 2", 'yes'), ("TEXT 3", 'no'),
    ("TEXT 4", 'no'), ("TEXT 5", 'yes')
    ]


# Expected Output:
# [({"TEXT 1": 'no'}, "Comment 1"),
#  ({"TEXT 2": 'yes'}, "Comment 2")]


def newdata(data_arg):
    print([
        ({tup[0]: tup[1]}, f'Comment {tup[0].split()[1]}') for tup in data_arg
        ])


newdata(data)

This will get the expected output for all tuples in the dictionary, “print” can be switched to return if needed.

Another approach:

def func(oldstring):
    ANS = []
    cmt = 0
    for i in oldstring:
        new_dic = {}
        cmt += 1
        new_dic[i[0]] = i[1]
        ANS.append((new_dic, 'comment' + str(cmt)))
    return ANS


print(func(data))

These may solve the issue.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement