Home > other >  How to find the values of a key in a nested list of dictionaries in Python
How to find the values of a key in a nested list of dictionaries in Python

Time:11-30

This is my data structure. I have 3000 instances of 'product' within the 'clothes list'. Each contains another list of dictionaries that stores the reviews.

clothes_list = 
[
  {
    "ID": "1000201",
    "Name": "Clothes Name",
    "Price": 24.1,
    "Category": "Trousers"
    "Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
                  {'User': 'username341', 'Review': 'Some review 2' , 'Score': 4}
                  {'User': 'username34841', 'Review': 'Some review 3' , 'Score': 2}
               ]
  },

  {
    "ID": "1003801",
    "Name": "Clothes Name",
    "Price": 29.1,
    "Category": "Trousers"
    "Reviews": [{'User': 'username1200', 'Review': 'some review', 'Score': 2}
                  {'User': 'username341', 'Review': 'Some review 4' , 'Score': 7}
                  {'User': 'username34841', 'Review': 'Some review 5' , 'Score': 4}
               ]
  },
  
]

I am attempting to iterate through all the reviews in the dictionary and return all the reviews written by a particular username.

My Two attempts below output the same error.

username = "username341"
reviews = next((review for review in clothess_list if review["Reviews"]["User"] == username))]
values = [a_dict["Reviews"][username] for a_dict in clothes_list]

The Error

TypeError: list indices must be integers or slices, not str

CodePudding user response:

Your logic review["Reviews"]["User"] can't be iterable because Reviews is a list of dictionaries. You can't directly call dictionary without putting any index of list.

username = "username341"
reviews=next( user for review in clothes_list for user in review['Reviews'] if user['User']==username)
    
print(reviews)

Output

{'User': 'username341', 'Review': 'Some review 2', 'Score': 4}

CodePudding user response:

Your attempts are incorrect because you are treating a list as a dictionary. The following snippet solves your problem, but it is probably not the best way to do so.

reviews = next(
    c for c in clothes_list 
    if any(review for review in c["Reviews"] if review["User"] == username)
)

CodePudding user response:

I find it easiest just to write it across multiple lines as if I were writing multiple for loops

[review
 for clothes_item in clothes_list
 for review in clothes_item["Reviews"]
 if review["User"] = username
]

You can of course turn this into a generator if want by replacing the [] with ()

CodePudding user response:

Try this:

clothes_list = [{
    "ID": "1000201",
    "Name": "Clothes Name",
    "Price": 24.1,
    "Category": "Trousers",
    "Reviews": [{
        "User": "username1200", "Review": "some review", "Score": 2
    }, {'User': 'username341', 'Review': 'Some review 2', 'Score': 4},
        {'User': 'username34841', 'Review': 'Some review 3', 'Score': 2},{
        "User": "username1200", "Review": "some review 4 by same user", "Score": 2
    },]
}]


def get_reviews(username):
    a = []
    for i in range(len(clothes_list)):
        for x in clothes_list[i]["Reviews"]:
            if x["User"] == username:
                a.append(x)

    return a

print(get_reviews("username1200"))

Everyone else's answers are also correct, just the dataset contains only one review from each user. I have editted the dataset to contain 2 reviews from username1200

Try the other answers with the dataset i have provided and it'll return 2 dicts in a list.

  • Related