list in dictionary python code example
Example 1: python 3.7 insert at place in dict
def insert_item(dic, item={}, pos=None):
"""
Insert a key, value pair into an ordered dictionary.
Insert before the specified position.
"""
from collections import OrderedDict
d = OrderedDict()
if not item or not isinstance(item, dict):
print('Aborting. Argument item must be a dictionary.')
return dic
if not pos:
dic.update(item)
return dic
for item_k, item_v in item.items():
for k, v in dic.items():
if k == pos:
d[item_k] = item_v
d[k] = v
return d
d = {'A':'letter A', 'C': 'letter C'}
insert_item(['A', 'C'], item={'B'})
insert_item(d, item={'B': 'letter B'})
insert_item(d, pos='C', item={'B': 'letter B'})
Example 2: python list of dictionaries
new_player1 = { 'firstName': 'LaMarcus', 'lastName': 'Aldridge', 'jersey': '12', 'heightMeters': '2.11', 'nbaDebutYear': '2006', 'weightKilograms': '117.9'}
new_player2 = { 'firstName': 'LeBron', 'lastName': 'James', 'jersey': '2', 'heightMeters': '2.03', 'nbaDebutYear': '2003', 'weightKilograms': '113.4' }
new_player3 = { 'firstName': 'Kawhi', 'lastName': 'Leonard', 'jersey': '2', 'heightMeters': '2.01', 'nbaDebutYear': '2011', 'weightKilograms': '104.3' }
nba_players = []
nba_players.append(player)
nba_players.append(new_player1)
nba_players.append(new_player2)
nba_players.append(new_player3)
Example 3: python dictionary with list
dictionary = {"one": [1, 2, 3, 4, 5], "two": "something"}
print(dictionary["one"][2])
3