How to combine two dictionaries in Python without duplicates

Viewed 40

Hey I'm trying to combine two dictionaries filled with JSON data without duplicates. I'm using Flask and Jinja2 to build an api to fetch json data from an api and post it on a web page, I want to be able to filter based off of tags and then combine the results every time I make a request. Currently I'm able to filter based off of tags chosen by submitting buttons on Jinja but I'm having trouble getting it to combine when I select a new tag, when a new tag is selected it filters only using that tag and doesn't combine the dictionary from the previous result.

main.py:

@app.route('/api', methods=['GET', 'POST'])
def add_tag():
name = request.form['tags']
form = APInameForm()
url= 'https://api.hatchways.io/assessment/blog/posts?tag='+name
try:
        api = requests.get(url).json()
        api = api['posts']
        ilist = []
        nlist = []            

        for i in api:
            ilist.append(i)



        if not ilist:
            output = '{<br>'
            output = output + '"error": "Tags parameter is required" <br>'
            output = output + '}'
            return output

        return render_template('/index.html', test=ilist)

except requests.ConnectionError:
        return "Connection Error"




@app.route('/')
def index():
   return render_template("index.html")

index.html:

     {% extends 'base.html' %}

     {% block content %}

    <form class="text-center pt-3" method="POST" action="/api">
      <input type="text" class="form-control" placeholder="Search" name="tags">
      <input type="submit" value="Search" />

    </form>

   <br/><br/><br/>
   <h1>Recommended Tags:</h1>
    <form class="form-inline" method="POST" action="/api">

    <div class="control">
     <input type="submit" class="btn btn-primary mb-2" name="tags" value="tech">
    </input>
    </div> 

    <div class="control">
     <input type="submit" class="btn btn-primary mb-2" name="tags" value="history">
     </input>
    </div> 

    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="startups">
        </input>
    </div>
    
    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="health">
        </input>
    </div> 
    
    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="science">
        </input>
    </div> 

    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="design">
        </input>
    </div>
    
    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="culture">
        </input>
    </div> 

    <div class="control">
        <input type="submit" class="btn btn-primary mb-2" name="tags" value="history">
        </input>
    </div> 

  </form>

   <br/><br/><br/>

  <code>
      {<br>
"posts": [{<br>
 {% for item in test %}
     
     "id": {{ item.id }}<br>
     "author": {{ item.author }}<br>
     "autherId": {{ item.authorId }}<br>
     
     "likes": {{ item.likes }}<br>
     "popularity" :{{ item.popularity }}<br>
     "reads": {{ item.reads }}<br>
     "tags": {{ item.tags }}<br><br>
  
    {% endfor %}
     }
    ]
   </code>

    {% endblock %}
2 Answers

You need to store the previous data somewhere outside these functions to be able to use it in later calls to them. Temporarily, that could be in a variable defined at the top level in your module (.py file).

If you need it to persist longer (across worker threads, sessions or restarts of your custom server), you might need to write to a file or database.

To merge the JSON dictionaries you can use the dict.update method (see official docs).

Given two dict instances d1, d2, calling d1.update(d2) will merge d2 into d1, overwriting values for any keys that are the same.


combined_data = {}

@app.route('/api', methods=['GET', 'POST'])
def add_tag():
    response = requests.get(url)
    data = response.json()
    combined_data.update(data)

    # ..now render combined_data

Related