1

I have got a list in python

issuelist=[["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]

I want to append the values of this list into another list in such a way that if value of issuelist[x][1]==issuelist[y][1] I can get something like this

Buildlist=[["k1","k3","k7"],["k2","k4","k5"],["k6"]]

issuelist=[["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
count=len(issuelist)
buildlist = [[]]* count
for i in range(len(issuelist)):
    for j in range(len(issuelist)):
        if issuelist[i][1]==issuelist[j][1]:
            buildlist[i].append(issuelist[j][0])

This is what I have tried now but I could not get the desirerd result. Any help would be appreciated

2
  • This is input => issuelist = [["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]. What kind of output you are expecting ? Commented May 22, 2019 at 9:02
  • [["k1","k3","k7"],["k2","k4","k5"],["k6"]] Commented May 22, 2019 at 9:03

2 Answers 2

4

Use itertools.groupby

Ex:

from itertools import groupby

issuelist = [["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
result = {k: [i[0] for i in v ]for k, v in groupby(sorted(issuelist, key=lambda x: x[1]), lambda x: x[1])}
print(result)
print(list(result.values()))

Output:

{'v1': ['k1', 'k3', 'k7'], 'v2': ['k2', 'k4', 'k5'], 'v3': ['k6']}
[['k1', 'k3', 'k7'], ['k2', 'k4', 'k5'], ['k6']]
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

from collections import defaultdict
issuelist = [["k1","v1"],["k2","v2"],["k3","v1"],["k4","v2"],["k5","v2"],["k6","v3"],["k7","v1"]]
result = defaultdict(list)
for inner_list in issuelist:
    result[inner_list[1]].append(inner_list[0])

result_array = list(result.values())
rint(presult_array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.