-1

I have list of dict from which I need to convert all the dict values into list of list without changing the order.

I used empty list and tried to append dict values using for loop but its not in order.

For example:

    result = [{'Project': 'ABC','Employee': 'MNK','Project': 'ABC','Project': 'ABC'}]

I want in below format:

    answer = [['ABC'],['MNK'],['ABC'],['ABC']]

I used below code:

    answer =[]
    for i,j in enumerate(result):
        answer .append(result[i].values())

What I got is

    answer = [['MNK'],['ABC'],['ABC'],['ABC']]

Expected answer is

    answer = [['ABC'],['MNK'],['ABC'],['ABC']]

Note: I am looking for code which gives expected answer, I checked other questions, none of them related to this. Right suggestions and codes are accepted. Thanks.

2 Answers2

2

Based on your comment with the new list:

Using map():

result = [{'T_Project': 'ABC','T_Employee': 'MNK','T_Project1': 'ABC','T_Project2': 'ABC'}]

print(list(map(lambda x: x.values(), result)))

Using list-comprehension:

print(list(x.values() for x in result))

OUTPUT:

[dict_values(['ABC', 'MNK', 'ABC', 'ABC'])]

pyFiddle

EDIT:

Python 2.x:

from collections import OrderedDict

d = OrderedDict()
d['T_Project'] = 'ABC'
d['T_Employee'] = 'MNK'
d['T_Project1'] = 'ABC'
d['T_Project2'] = 'ABC'

print(d)
print(list(d.values()))

OUTPUT:

OrderedDict([('T_Project', 'ABC'), ('T_Employee', 'MNK'), ('T_Project1', 'ABC'), ('T_Project2', 'ABC')])
['ABC', 'MNK', 'ABC', 'ABC']

pyFiddle 2.x

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

I will assume that you've written your question input dictionary wrong and I will assume it looks like this:

result = [
    {'Project': 'ABC'},
    {'Employee': 'MNK'},
    {'Project': 'ABC'},
    {'Project': 'ABC'}
]

x = [list(d.values()) for d in result]

print(x)

Which will yield what you want [['ABC'], ['MNK'], ['ABC'], ['ABC']]

andreihondrari
  • 5,743
  • 5
  • 30
  • 59