user1821176
user1821176

Reputation: 1191

Using a for loop to insert list values in empty lists within a nested dictionary

I have a nested dictionary:

my_dict = {
1: {'player_id': 1,
'player_name': 'Bryan_Demapan',
'time_played': 0.0,
'player_pokemon': {},
'gyms_visited': []},
2: {'player_id': 2,
'player_name': 'Tom Syneal',
'gyms_visited': [],
'player_pokemon': {},
'time_played': 0.0}}

Suppose I have a list

new_list = ['A', 'B', 'C']

How would I make a for loop statement that inserts my new list into all the empty lists with the key 'gyms_visited'?

the new dictionary should look like this

my_dict = {
1: {'player_id': 1,
'player_name': 'Bryan_Demapan',
'time_played': 0.0,
'player_pokemon': {},
'gyms_visited': ['A', 'B', 'C']},
2: {'player_id': 2,
'player_name': 'Tom Syneal',
'gyms_visited': ['A', 'B', 'C'],
'player_pokemon': {},
'time_played': 0.0}}

Upvotes: 3

Views: 727

Answers (4)

RoadRunner
RoadRunner

Reputation: 26315

You can also just extend() the list:

for key in my_dict:
    my_dict[key]['gyms_visited'].extend(new_list)

and as you can see here, all the lists have a different id() and not referencing the same object:

print(id(new_list))
# 2704861952904

for key in my_dict:
    print(id(my_dict[key]['gyms_visited']))
# 2704833143368
# 2704833143432

In terms of performance, list.extend() is O(N), where N = 3 is the length of list you want to extend. This most likely is a series of list.append() calls, which are O(1) each.

This will be the same for copying using [:] or .copy(), which is O(N).

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71570

Try this:

print({idx:{k:(new_list if k=='gyms_visited' else v) for k,v in i.items()} for idx,i in enumerate(my_dict.values(),1)})

Nested dictionary comprehension would work.

Output:

{1: {'player_id': 1, 'player_name': 'Bryan_Demapan', 'time_played': 0.0, 'player_pokemon': {}, 'gyms_visited': ['A', 'B', 'C']}, 2: {'player_id': 2, 'player_name': 'Tom Syneal', 'gyms_visited': ['A', 'B', 'C'], 'player_pokemon': {}, 'time_played': 0.0}}

I actually like @aydow's solution, In addition to it, you can do it like:

for k,v in data.items():
   v['gyms_visited']=new_list[:]

Or:

import copy
for k,v in data.items():
   v['gyms_visited']=copy.deepcopy(new_list)

Upvotes: 0

aydow
aydow

Reputation: 3801

Just iterate over the values of my_dict and assign new_list to the key 'gyms_visited'

In [529]: for k, v in my_dict.items():
     ...:     v['gyms_visited'] = new_list.copy()
     ...:

In [530]: my_dict
Out[530]:
{1: {'gyms_visited': ['A', 'B', 'C'],
  'player_id': 1,
  'player_name': 'Bryan_Demapan',
  'player_pokemon': {},
  'time_played': 0.0},
 2: {'gyms_visited': ['A', 'B', 'C'],
  'player_id': 2,
  'player_name': 'Tom Syneal',
  'player_pokemon': {},
  'time_played': 0.0}}

If you were to simply assign new_list then you will come into trouble as soon as you change any value in new_list

In [529]: for k, v in my_dict.items():
     ...:     v['gyms_visited'] = new_list
     ...:

In [531]: new_list[1] = 100

In [532]: my_dict
Out[532]:
{1: {'gyms_visited': ['A', 100, 'C'],
  'player_id': 1,
  'player_name': 'Bryan_Demapan',
  'player_pokemon': {},
  'time_played': 0.0},
 2: {'gyms_visited': ['A', 100, 'C'],
  'player_id': 2,
  'player_name': 'Tom Syneal',
  'player_pokemon': {},
  'time_played': 0.0}}

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71451

You can use a dictionary comprehension:

new_list = ['A', 'B', 'C']
data = {1: {'player_id': 1, 'player_name': 'Bryan_Demapan', 'time_played': 0.0, 'player_pokemon': {}, 'gyms_visited': []}, 2: {'player_id': 2, 'player_name': 'Tom Syneal', 'gyms_visited': [], 'player_pokemon': {}, 'time_played': 0.0}}
new_data = {a:{c:[i for i in new_list if i not in d] if c == 'gyms_visited' else d \
    for c, d in b.items()} for a, b in data.items()}

Output:

{
  "1": {
    "player_id": 1,
    "player_name": "Bryan_Demapan",
    "time_played": 0.0,
    "player_pokemon": {},
    "gyms_visited": ["A", "B", "C"]
 },
 "2": {
    "player_id": 2,
    "player_name": "Tom Syneal",
    "gyms_visited": ["A", "B", "C"],
    "player_pokemon": {},
    "time_played": 0.0
   }
}

Upvotes: 0

Related Questions