I have the following data, however I want to create a dictionary using a foor loop.
JavaScript
x
2
1
data = [("TEXT 1", 'no'), ("TEXT 2", 'yes'), ("TEXT 3", 'no'), ("TEXT 4", 'no'), ("TEXT 5", 'yes')]
2
Is it possible to do that?
I need a dictionary with this structure:
JavaScript
1
3
1
[({"TEXT 1": 'no'}, "Comment 1"),
2
({"TEXT 2": 'yes'}, "Comment 2")]
3
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:
JavaScript
1
19
19
1
data = [
2
("TEXT 1", 'no'), ("TEXT 2", 'yes'), ("TEXT 3", 'no'),
3
("TEXT 4", 'no'), ("TEXT 5", 'yes')
4
]
5
6
7
# Expected Output:
8
# [({"TEXT 1": 'no'}, "Comment 1"),
9
# ({"TEXT 2": 'yes'}, "Comment 2")]
10
11
12
def newdata(data_arg):
13
print([
14
({tup[0]: tup[1]}, f'Comment {tup[0].split()[1]}') for tup in data_arg
15
])
16
17
18
newdata(data)
19
This will get the expected output for all tuples in the dictionary, “print” can be switched to return if needed.
Another approach:
JavaScript
1
13
13
1
def func(oldstring):
2
ANS = []
3
cmt = 0
4
for i in oldstring:
5
new_dic = {}
6
cmt += 1
7
new_dic[i[0]] = i[1]
8
ANS.append((new_dic, 'comment' + str(cmt)))
9
return ANS
10
11
12
print(func(data))
13
These may solve the issue.