Home > Blockchain >  How to make a list of dict values I extracted to be in single line
How to make a list of dict values I extracted to be in single line

Time:09-25

I want to write the values in a dictionary in one line as a list.

If I do this:

dict = [ {'Value': 'test1'},
         {'Value': 'test2'},
         {'Value': 'test3'},
         {'Value': 'test4'}]


for a in dict:
    print(a['Value'])

The output I get is:

test1
test2
test3
test4

Now, I want those tests to write in one line like this: [test1, test2, test3, test4]

If I do this:

x=[]
for a in dict:
    print(a['Value'])
    x.append(a['Value'])
    print(x)

The output is:

test1
['test1']
test2
['test1', 'test2']
test3
['test1', 'test2', 'test3']
test4
['test1', 'test2', 'test3', 'test4']

How can I write the output that is in one row (it doesn't have to be a list? I just need to be able to write it in a excel cell afterwards using xlsxwriter)

CodePudding user response:

So using some of the code you already tried:

x=[]
for a in dict:
    x.append(a['Value'])

line_to_print = " ".join(x)
print(line_to_print)

Now they should be all on the same line!

Output:

test1 test2 test3 test4

CodePudding user response:

Assuming all you want to do is remove the quotes, if I'm reading the question right, you implement the change below:

x=[]

for a in dict:
    x.append(a['Value'])

x1 = str(x).replace("'", "")

x1 would be the string of values as a list without the quotes. If this wasn't what you meant, could you please elaborate more on what you're trying to do here?

CodePudding user response:

data = [ {'Value': 'test1'},
         {'Value': 'test2'},
         {'Value': 'test3'},
         {'Value': 'test4'}]

result = []
for item in data:
    for val in item.values():
        result.append(val)

Output: ['test1', 'test2', 'test3', 'test4']

CodePudding user response:

you could use a comprehension with parameter unpacking to the print function:

data = [ {'Value': 'test1'},
         {'Value': 'test2'},
         {'Value': 'test3'},
         {'Value': 'test4'}]

print(*(d['Value'] for d in data))

test1 test2 test3 test4

with your own separator if needed ...

print(*(d['Value'] for d in data),sep=', ')

test1, test2, test3, test4

or make a string of it before printing:

print(" ".join(d['Value'] for d in data)) 

test1 test2 test3 test4

You can also use your own separator and enclose it in brackets:

print("[" ", ".join(d['Value'] for d in data) "]") 

[test1, test2, test3, test4]
  • Related