users = [
{'id': 0, "name": "Hero"},
{'id': 1, "name": "Dunn"},
{'id': 2, "name": "Sue"},
{'id': 3, "name": "Chi"},
{'id': 4, "name": "Thor"},
{'id': 5, "name": "Clive"},
{'id': 6, "name": "Hicks"},
{'id': 7, "name": "Devin"},
{'id': 8, "name": "Kate"},
{'id': 9, "name": "Klein"},
]
# list of users
friendship_pairs = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4), (4, 5),
(5, 6), (5, 7), (6, 8), (7, 8),
(8, 9)] # list of friendship pairs
# it is easy to make a dictionary list of friendships for the IDs as the friendship_pairs and written in terms of IDs
# what if I wanted this dict to show for example "Hero": ["dunn","Sue"] instead of 0:[1,2]
friendships = {user['id']: [] for user in users}
for i, j in friendship_pairs:
friendships[i].append(j)
friendships[j].append(i)
display(friendships)
# I made a dictonary of intergers:names
user_Ids = list(user['id'] for user in users)
user_Names = list(user['name'] for user in users)
converter = dict(zip(user_IDS, user_Names))
# How can I use this to turn 'friendship_pairs' into something like 'friendship_pairs_names'
# which has the same information has friendship_pairs but uses their names
I would like to be able to take the input of friendship_pairs and return a variable that has the same information where the ids values from users is replaced with name values from users so that I can make the same dictionary displayed in ids, with names. Open to any suggestion on faster or cleaner methods.
Write a dictionary that maps an id to a name. like this:
names = {user['id']:user['name'] for user in users}
Then you can create a dictionary in the same way that you created one for the ids but with names[id] instead of id, like so:
users =[
{'id':0, "name":"Hero"},
{'id':1, "name":"Dunn"},
{'id':2, "name":"Sue"},
{'id':3, "name":"Chi"},
{'id':4, "name":"Thor"},
{'id':5, "name":"Clive"},
{'id':6, "name":"Hicks"},
{'id':7, "name":"Devin"},
{'id':8, "name":"Kate"},
{'id':9, "name":"Klein"},
]
names = {user['id']:user['name'] for user in users}
friendship_pairs = [(0,1),(0,2),(1,2),(1,3),(2,3),(3,4),(4,5),(5,6),(5,7),(6,8),(7,8),(8,9)]
friendships = {user['name']: [] for user in users}
for i, j in friendship_pairs:
friendships[names[i]].append(names[j])
friendships[names[j]].append(names[i])
print(friendships)
output:
{
'Hero': ['Dunn', 'Sue'],
'Dunn': ['Hero', 'Sue', 'Chi'],
'Sue': ['Hero', 'Dunn', 'Chi'],
'Chi': ['Dunn', 'Sue', 'Thor'],
'Thor': ['Chi', 'Clive'],
'Clive': ['Thor', 'Hicks', 'Devin'],
'Hicks': ['Clive', 'Kate'],
'Devin': ['Clive', 'Kate'],
'Kate': ['Hicks', 'Devin', 'Klein'],
'Klein': ['Kate']
}
You could also use setdefault
as to not need the the {user['name']: [] for user in users}
dictionary comprehension and instead do this:
friendships = {}
for i, j in friendship_pairs:
friendships.setdefault(names[i], []).append(names[j])
friendships.setdefault(names[j], []).append(names[i])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments