nested dictionary with list of tuples as values from DATA file in python

LMHull

Please, help. I have a data file with 4 columns (userid, movieid, score, timestamp) that looks like this:

196 242 3   881250949
186 302 3   891717742
22  377 1   878887116
196 51  2   880606923
62  257 2   879372434

I am trying to create a nested dictionary that should look like this:

users = {'196': [('242', '3'), ('51', '2')], '186': ['302','3'] ...}

My code only picks up one tuple (movieid, score) for each userid:

def create_users_dict():
    try:
        users = {}
        for line in open('u.data'):
            (id, movieid, rating, timestamp) = line.split('\t')[0:4]
            users[id] = (movieid, rating)
    except IOError as ioerr:
        print('There is an error with the file:' + str(ioerr))
    return users
users = create_users_dict()

users = {'196': ('51', '2'), '186': ('302', '3')...}

Dani Mesejo

Use setdefault:

def create_users_dict():
    try:
        users = {}
        for line in open('u.data'):
            uid, movie_id, rating, timestamp = line.split()
            users.setdefault(uid, []).append((movie_id, rating))
        return users
    except IOError as ioerr:
        print('There is an error with the file:' + str(ioerr))
users = create_users_dict()

print(users)

Output

{'196': [('242', '3'), ('51', '2')], '62': [('257', '2')], '186': [('302', '3')], '22': [('377', '1')]}

A possible alternative is to check if the key (uid) is in the dictionary, in case is missing initialize the value with the empty list and then simply append.

def create_users_dict():
    try:
        users = {}
        for line in open('u.dat'):
            uid, movie_id, rating, timestamp = line.split()
            if uid not in users:
                users[uid] = []
            users[uid].append((movie_id, rating))
        return users
    except IOError as ioerr:
        print('There is an error with the file:' + str(ioerr))

As a side note you should not use id as a name because it shadows the built-in function id.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Create a list of values from nested dictionary Python

Converting nested list and a list of tuples into a dictionary python

Python: from list of tuples to dictionary of tuples

multi nested dictionary from tuples in python

Sort an item in a list of tuples in the values of a dictionary with Python

Fetch specific values from nested tuples in a list

extract values from nested dictionaries in a list of tuples

Python - Merge list of tuples from nested list

List of tuples to nested dictionary based on tuple's values

Python: create a nested dictionary from a list of parent child values

Python - list of tuples from file

list comprehension to build a nested dictionary from a list of tuples

How to create list of tuples from dictionary in python?

Python - Generate a dictionary(tree) from a list of tuples

Python: Extract values from a text file to create nested dictionary

Convert a nested dictionary into list of tuples

Convert nested dictionary into list of tuples

Getting a list of values from dictionary when values are tuples within lists?

Extracting a nested tuples from list (Python)

Dictionary with list of tuples Python

Arbitrarily nested dictionary from tuples

Pythonically unpacking nested list values from a dictionary

Get values from a nested dictionary to a list

Retrieve values from list of nested dictionary

Match elements in nested list with values from dictionary

Selection of Some Values in List from Nested Dictionary

Converting a dictionary into a list of Values/Tuples

Pandas - create data frame from nested key values and nested list in the dictionary

Nested Dictionary Comprehension in Python with List of Values