Reputation: 89
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.
Upvotes: 0
Views: 330
Reputation: 48
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.
Upvotes: 3
Reputation: 41
I hope this method will help.
data = [("TEXT 1", 'no'), ("TEXT 2", 'yes'), ("TEXT 3", 'no'), ("TEXT 4", 'no') ("TEXT 5", 'yes')]
result = []
for k,v in data:
r = f"comment {k[5]}"
dat={}
dat[k]=v
tup = (dat,r)
result.append(tup)
Upvotes: 0
Reputation: 27485
Just turn the tuples into dicts and for the comments you can use enumerate
to get the numbering:
output = [(dict(t), f'Comment {i}') for i, t in enumerate(data)]
Upvotes: 0