Combine two lists of tuples by key

user31027

I have two lists of two elements tuples. First element of tuple is ID and second is some kind of value. Type of value depends on list.

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

What is the easiest way to combine them into:

lst3 = [ ('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]
tobias_k

I suggest you turn those lists of tuples into dictionaries first. Then, assuming that both lists contain the same "keys", you can use a simple list comprehension to get the respective values from the two dictionaries.

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 
dict1 = dict(lst1)
dict2 = dict(lst2)
lst3 = [(k, dict1[k], dict2[k]) for k in sorted(dict1)]

Note that dictionaries have no fixed order. If you want to preserve the order the keys had in lst1, you might also use this, as suggested in comments:

lst3 = [(k, v, dict2[k]) for k, v in lst1]

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Combine/Mix two lists of words

분류에서Dev

merge two tuples with same key

분류에서Dev

combine two keys to one key in mongodb

분류에서Dev

Adding tuples in lists in Python

분류에서Dev

Use tuples/lists as array indices (Python)

분류에서Dev

How to extract tuples from a list of lists in Haskell

분류에서Dev

Combine two queries in Oracle

분류에서Dev

combine multiple lists horizontally into a single list

분류에서Dev

How to combine two tables in R?

분류에서Dev

combine two different queries into one

분류에서Dev

Combine two commands into a single command

분류에서Dev

In Python, is there a way to sort a list made of lists and tuples, consistently?

분류에서Dev

How to combine two selects or two querys?

분류에서Dev

Iterating two lists in a compact way

분류에서Dev

Sending two lists via socket

분류에서Dev

How to merge lists by two together?

분류에서Dev

Zip two lists into text file

분류에서Dev

Add two values from two different Lists

분류에서Dev

Combine data of objects in NSMutableArray with same key

분류에서Dev

How can I copy and combine several .txt lists in alphabetical order?

분류에서Dev

How to combine values composed of lists with common items in a dictionary using Python?

분류에서Dev

How to combine the results of two different queries with mongoose?

분류에서Dev

How to dynamically combine two interfaces to pass to RealProxy

분류에서Dev

Combine two dataframes one above the other

분류에서Dev

Python combine two for loops and not over repeat

분류에서Dev

combine two array string to make a list

분류에서Dev

Combine two POSTs using global variables

분류에서Dev

How can I combine these two statements?

분류에서Dev

How can I combine two files on Windows?

Related 관련 기사

뜨겁다태그

보관