How to merge two dictionaries?

Viewed 58

I'm building a program powered by Spotify API with Spotipy library. I want to get a user's saved tracks in their Spotify library. Spotipy has a function called current_user_saved_tracks and does that exactly. But there's a track limit which is 50. I wanted to get 100 tracks so I used this function two times with different offsets (Offset indicates the starting point of getting tracks.).

results1 = sp.current_user_saved_tracks(limit=50, offset=0, market=None)

and

results2 = sp.current_user_saved_tracks(limit=50, offset=50, market=None)

Then I tried to merge these two dictionaries(?).

results = dict(list(results1.items()) + list(results2.items()))

But whenever I run my program and take a look at my sqlite database where track information stores, only the 2nd dictionary (results2) shows up for 2 times. I get 100 tracks indeed but, I get the second part 2 times.

I guess there's some kind of problem with my merging system. Help me if you know how to get that 100 distinct tracks.

EDIT

This one shows results2, 2 times (Basically nothing has changed.):

results = results1 | results2 

This one shows results2, just once (The track amount is now 50.):

results = {**results1, **results2}

FINAL EDIT

I've tried all of your solutions but the problem remains unresolved. So I wrote the related for loops for results1 and results2 separately and it kind of worked (instead of 100 tracks, now I get 200 but I got that distinct 100 tracks). But thank you for your time!

1 Answers

There are two ways to merge two dictionaries in Python:

In [1]: numbers = {"a": 1, "b": 2, "c": 3}

In [2]: letters = {"1": "a", "2": "b", "3": "c"}

In [3]: {**numbers, **letters}
Out[3]: {'a': 1, 'b': 2, 'c': 3, '1': 'a', '2': 'b', '3': 'c'}

In [4]: numbers | letters
Out[4]: {'a': 1, 'b': 2, 'c': 3, '1': 'a', '2': 'b', '3': 'c'}

In [5]: # Above is Python 3.10+ only

If you have Python 3.10+, the second is preferred.

Related