Reputation: 29
I am trying to figure out the best way to add keys and values in a dictionary. A little context on my problem. I am trying to do graph traversal where each node is a subpage of a basic HTML website. I am looking for the links that each page contains and where they go. I am struggling trying to figure out how to do this iteratively.
Example of what I am talking about:
Graph = {Current_Page : {links that are on this page}
Graph = {page1: {'page2', 'page3' page4'}
Next I want to go to page 2 and find all the link it has access to and add those to the graph dictionary.
Graph = {page2: {'page1', 'page3' page4', 'page5'}
I am fairly new to python, but I will try my best to understand.
Upvotes: 0
Views: 200
Reputation: 29
To anyone who may look at this for a solution this is what I did. I compiled a list of all the webpages that I wanted to get the links on that page to, it is stored in a list called pages
. I also used a getLinks
method that would fetch the links for me.
graph = {}
for value in pages:
graph[value] = getLinks(value)
This returned a dictionary with the formatting in the original problem statement.
Upvotes: 0
Reputation: 6045
A good way to do is to have all the pages you want to get links for in a list (I assumed pages
) and have a function for getting links from that page as get_links()
. You can then use following snippet as a readable and reliable approach to achieve what you are trying to achieve:
Graph = {}
for page, page_number in enumerate(pages):
Graph['page' + page_number] = get_links(page)
Upvotes: 1
Reputation: 35
You can try simply looping through each page, finding the links and then adding them to the dictionary.
Graph = {}
for pageNumber in range(0, pagesNumber, 1):
linkList = ##I think you figured this part out?
Graph['page' + pageNumber] = linkList
That should add it to the dictionary. Just add in the code to find the links and fill in all the variables, good luck!
Upvotes: 1