Python: converting a list of tuples to dictionary with some conditions

convert list of key value pairs to dictionary python
convert list of tuples to dictionary python
python list of tuples to dict of lists
python convert list to dictionary keys
python convert list to dictionary with index
convert list to dictionary python
convert list of dictionaries to dictionary python
convert nested list to dictionary python

I created a list like this:

Book = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End','sold'), 
 (25, '2009-01-01', 'Start'), (25, '2009-11-14', 'End', 'returned'),
 (26, '2010-04-03', 'Start'), (26, '2010-10-11', 'End', 'sold'),...]

I want to convert it to a dictionary like this:

bookDict = { 24: {'Start': '2008-10-30', 'End': '2008-12-20','reason':'sold'},
  25: {'Start': '2009-01-01', 'End': '2009-11-14','reason':'returned'},
  26: {'Start': '2010-04-03', 'End': '2010-10-11','reason':'sold'},...}

For each key in the dictionary which is the first value of tuples in the Book list(it is a code), I want to have two tuples as values of each key. One of them is related to the 'start' point and the other one is related the 'End' point of that specific code.

I have another question as well. For some of the codes There is more than one 'End' point with different dates. I want to keep only the End point with the later date. some thing like this:

Book = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End', 'sold'), 
 (24, '2009-02-04', 'End', 'sold'), (24, '2009-11-25', 'End', 'sold')]

For above example dictionary should keep this:

bookDict = { 24: {'Start': '2008-10-30', 'End': '2009-11-25','reason':'sold'},

Can anyone help me please?

Here is a solution that satisfies both criterions.

Everytime it encoutners a new book id, it creates a dict for it and fills it in as it encounters data in your list.

As for multiple End entries, your date format allows to use string comparison to get the latest date.

books = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End','sold'),
 (25, '2009-01-01', 'Start'), (25, '2009-11-14', 'End', 'returned'),
 (26, '2010-04-03', 'Start'), (26, '2010-10-11', 'End', 'sold'),
 (26, '2011-10-11', 'End', 'returned')] # The latest 'End' entry should be picked

bookDict = {}

for info in books:
    id_ = info[0]
    type_ = info[2]

    book = bookDict.setdefault(id_, {})

    if type_ == 'Start':
        book[type_] = info[1]

    elif type_ == 'End' and info[1] > book.get(type_, ''):
        book[type_] = info[1]
        book['reason'] = info[3]

Output:

bookDict
# {24: {'Start': '2008-10-30', 'End': '2008-12-20', 'reason': 'sold'},
#  25: {'Start': '2009-01-01', 'End': '2009-11-14', 'reason': 'returned'},
#  26: {'Start': '2010-04-03', 'End': '2010-10-11', 'reason': 'returned'}}

Python, Python | Convert a list of Tuples into Dictionary. Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to​  For each key in the dictionary which is the first value of tuples in the Book list(it is a code), I want to have two tuples as values of each key. One of them is related to the 'start' point and the other one is related the 'End' point of that specific code. I have another question as well.

You can use itertools.groupby, min, and max:

import itertools
def quantity_key(d):
  return list(map(int, d[1].split('-')))

Book = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End','sold'), (25, '2009-01-01', 'Start'), (25, '2009-11-14', 'End', 'returned'), (26, '2010-04-03', 'Start'), (26, '2010-10-11', 'End', 'sold')]
new_books = {a:list(b) for a, b in itertools.groupby(Book, key=lambda x:x[0])}
final_books = {a:{'Start':min(b, key=quantity_key)[1], 'End':max(b, key=quantity_key)[1], 'reason':max(b, key=quantity_key)[-1]} for a, b in new_books.items()}

Output:

{24: {'Start': '2008-10-30', 'End': '2008-12-20', 'reason': 'sold'}, 25: {'Start': '2009-01-01', 'End': '2009-11-14', 'reason': 'returned'}, 26: {'Start': '2010-04-03', 'End': '2010-10-11', 'reason': 'sold'}}

With more than two values for each key:

Book = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End', 'sold'), (24, '2009-02-04', 'End', 'sold'), (24, '2009-11-25', 'End', 'sold')]
new_books = {a:list(b) for a, b in itertools.groupby(Book, key=lambda x:x[0])}
final_books = {a:{'Start':min(b, key=quantity_key)[1], 'End':max(b, key=quantity_key)[1], 'reason':max(b, key=quantity_key)[-1]} for a, b in new_books.items()}

Output:

{24: {'Start': '2008-10-30', 'End': '2009-11-25', 'reason': 'sold'}}

Python, One among the problem of interconversion of data types in python is conversion of list of tuples to dictionaries, in which the keys are 1st element of tuple, which  Python | Convert a list of Tuples into Dictionary Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary.

You could do something like this:

for t in Book:
    index, date, marker, *rest = t
    entry = d.setdefault(index, {})
    end_date = entry.get("End", "1900-01-01")
    if marker == "Start" or date > end_date:
        entry[marker] = date
        if rest:
            entry["reason"] = rest[0]

Python : How to convert a list to dictionary ? – thispointer.com, Convert List items as keys in dictionary with enumerated value; Convert two lists to dictionary; Convert a list of tuples to dictionary. Convert a List  Given a dictionary, write a Python program to convert the given dictionary into list of tuples. Below are various methods to convert dictionary to list of tuples. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your

This answers the first part of OP's question only, although it can be adapted for the second.

You can use collections.defaultdict for an O(n) solution:

book = [(24, '2008-10-30', 'Start'), (24, '2008-12-20', 'End','sold'), 
        (25, '2009-01-01', 'Start'), (25, '2009-11-14', 'End', 'returned'),
        (26, '2010-04-03', 'Start'), (26, '2010-10-11', 'End', 'sold')]

from collections import defaultdict

d = defaultdict(dict)

for key, date, *data in book:
    d[key][data[0]] = date
    if len(data) == 2:
        d[key]['reason'] = data[1]

Alternatively, you can catch IndexError instead of testing for tuple length:

for key, date, *data in book:
    d[key][data[0]] = date
    try:
        d[key]['reason'] = data[1]
    except IndexError:
        continue

5. Data Structures, The list data type has some more methods. or to create a subsequence of those elements that satisfy a certain condition. If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized. >>> It is best to think of a dictionary as an unordered set of key: value pairs, with the  Given a list of tuples, write a Python program to convert it into list. Below are methods to convert list of tuples into list. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org.

Tuples, Without the comma Python treats ('a') as an expression with a string in Converting a dictionary to a list of tuples is a way for us to output the contents of a In some contexts, like a return statement, it is syntactically simpler to create a tuple  Let’s create a dictionary from this list with list elements as keys and values as integers from 0 to n-1 (n is size of list) i.e. Convert two lists to a dictionary. Suppose we have two lists i.e. Zip() accepts a number of iterable objects and returns a list of tuples.

Lesson 6, But what if you need to store a long list of information, which doesn't change For these three problems, Python uses three different solutions - Tuples, lists, and The values in a dictionary aren't numbered - they aren't in any specific order, Now to a sad situation - Snappy was shot by a neighbour, and eaten for their  Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements.

Lists and Tuples in Python – Real Python, You'll cover the important characteristics of lists and tuples in Python 3. You'd encounter a similar situation when using the in operator: What if you want to change several contiguous elements in a list at one time? There is another Python data type that you will encounter shortly called a dictionary, which requires as  But if you still want to use a list as a key, you must turn it into a tuple first. Because some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like

Comments
  • Perfect! Nice and clean! Thanks