简体   繁体   中英

Remove duplicates from list of dictionaries created using groupby itertools in Python

I want to remove some duplicates in my merged dictionary.

My data:

mongo_data = [{
 'url': 'https://goodreads.com/',
 'variables': [{'key': 'Harry Potter', 'value': '10.0'},
               {'key': 'Discovery of Witches', 'value': '8.5'},],
 'vendor': 'Fantasy' 
 },{
 'url': 'https://goodreads.com/',
 'variables': [{'key': 'Hunger Games', 'value': '10.0'},
               {'key': 'Maze Runner', 'value': '5.5'},],
 'vendor': 'Dystopia' 
 },{
 'url': 'https://kindle.com/',
 'variables': [{'key': 'Divergent', 'value': '9.0'},
               {'key': 'Lord of the Rings', 'value': '9.0'},],
 'vendor': 'Fantasy' 
 },{
 'url': 'https://kindle.com/',
 'variables': [{'key': 'The Handmaids Tale', 'value': '10.0'},
               {'key': 'Divergent', 'value': '9.0'},],
 'vendor': 'Fantasy' 
 }]

My code:

for key, group in groupby(mongo_data, key=lambda chunk: chunk['url']):
    search = {"url": key, "results": []}
    for vendor, group2 in groupby(group, key=lambda chunk2: chunk2['vendor']):
        result = {
            "genre": vendor,
            "data": [{'key': key['key'], 'value': key['value']} 
                     for result2 in group2
                     for key in result2["variables"]],
        }
        search["results"].append(result)
    searches.append(search)

My result:

[
  {
    "url": "https://goodreads.com/",
    "results": [
      {
        "genre": "Fantasy",
        "data": [
          {
            "key": "Harry Potter",
            "value": "10.0"
          },
          {
            "key": "Discovery of Witches",
            "value": "8.5"
          }
        ]
      },
      {
        "genre": "Dystopia",
        "data": [
          {
            "key": "Hunger Games",
            "value": "10.0"
          },
          {
            "key": "Maze Runner",
            "value": "5.5"
          }
        ]
      }
    ]
  },
  {
    "url": "https://kindle.com/",
    "results": [
      {
        "genre": "Fantasy",
        "data": [
          {
            "key": "Divergent",
            "value": "9.0"
          },
          {
            "key": "Lord of the Rings",
            "value": "9.0"
          },
          {
            "key": "The Handmaids Tale",
            "value": "10.0"
          },
          {
            "key": "Divergent",
            "value": "9.0"
          }
        ]
      }
      }
    ]
  }
]

I do not want any duplicates in my structure. I am not sure on how to take them out. My expected result can be seen below.

Expected result:

[
  {
    "url": "https://goodreads.com/",
    "results": [
      {
        "genre": "Fantasy",
        "data": [
          {
            "key": "Harry Potter",
            "value": "10.0"
          },
          {
            "key": "Discovery of Witches",
            "value": "8.5"
          }
        ]
      },
      {
        "genre": "Dystopia",
        "data": [
          {
            "key": "Hunger Games",
            "value": "10.0"
          },
          {
            "key": "Maze Runner",
            "value": "5.5"
          }
        ]
      }
    ]
  },
  {
    "url": "https://kindle.com/",
    "results": [
      {
        "genre": "Fantasy",
        "data": [
          {
            "key": "Divergent",
            "value": "9.0"
          },
          {
            "key": "Lord of the Rings",
            "value": "9.0"
          },
          {
            "key": "The Handmaids Tale",
            "value": "10.0"
          }
        ]
      }
      }
    ]
  }
]

Divergent is getting repeated in the last list of dictionaries. When I merged my dictionaries even the duplicates inside https://kindle.com/-->Fantasy got merged into one. Is there a way for me to remove the duplicate dictionary?

I want the https://kindle.com/ part to look like:

{
"url": "https://kindle.com/",
"results": [
  {
    "genre": "Fantasy",
    "data": [
      {
        "key": "Divergent",
        "value": "9.0"
      },
      {
        "key": "Lord of the Rings",
        "value": "9.0"
      },
      {
        "key": "The Handmaids Tale",
        "value": "10.0"
      }
    ]
  }
  }
]
}

You can try convert those dict to a set of tuple first and then convert back to a list of dict later:

mongo_data = [{
 'url': 'https://goodreads.com/',
 'variables': [{'key': 'Harry Potter', 'value': '10.0'},
               {'key': 'Discovery of Witches', 'value': '8.5'},],
 'vendor': 'Fantasy' 
 },{
 'url': 'https://goodreads.com/',
 'variables': [{'key': 'Hunger Games', 'value': '10.0'},
               {'key': 'Maze Runner', 'value': '5.5'},],
 'vendor': 'Dystopia' 
 },{
 'url': 'https://kindle.com/',
 'variables': [{'key': 'Divergent', 'value': '9.0'},
               {'key': 'Lord of the Rings', 'value': '9.0'},],
 'vendor': 'Fantasy' 
 },{
 'url': 'https://kindle.com/',
 'variables': [{'key': 'The Handmaids Tale', 'value': '10.0'},
               {'key': 'Divergent', 'value': '9.0'},],
 'vendor': 'Fantasy' 
 }]
from itertools import groupby
searches = []
for key, group in groupby(mongo_data, key=lambda chunk: chunk['url']):
    search = {"url": key, "results": []}
    for vendor, group2 in groupby(group, key=lambda chunk2: chunk2['vendor']):
        result = {
            "genre": vendor,
            "data": set((key['key'], key['value'])
                     for result2 in group2
                     for key in result2["variables"]),
        }
        result['data'] = [{"key": tup[0], "value": tup[1]} for tup in result['data']]
        search["results"].append(result)
    searches.append(search)
searches

Output:

[{'results': [{'data': [{'key': 'Harry Potter', 'value': '10.0'},
                        {'key': 'Discovery of Witches', 'value': '8.5'}],
               'genre': 'Fantasy'},
              {'data': [{'key': 'Maze Runner', 'value': '5.5'},
                        {'key': 'Hunger Games', 'value': '10.0'}],
               'genre': 'Dystopia'}],
  'url': 'https://goodreads.com/'},
 {'results': [{'data': [{'key': 'The Handmaids Tale', 'value': '10.0'},
                        {'key': 'Lord of the Rings', 'value': '9.0'},
                        {'key': 'Divergent', 'value': '9.0'}],
               'genre': 'Fantasy'}],
  'url': 'https://kindle.com/'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM