Search code examples
pythonjsonlistdictionaryenumerate

Python enumerating or something else?


I am starting with a json object that follows this example:

[
  {
    "url": "https://www.stackoverflow_greatquestions.com",
    "pages": 1
  },
  {
    "url": "https://www.stackoverflow_not-so-greatquestions.com",
    "pages": 3
  }
]

What I'm trying to accomplish is print the urls equal to the number of pages which I've done doing this:

url_list = []
for x in json:
    for y in range(x['pages']):
        url_list.append(x['url'])

I'm almost there, this is doing what I asked and printing out the urls, but I also want to number the output based on the value of pages.

So my end result would look like this:

"https://www.stackoverflow_greatquestions.com", 1,
"https://www.stackoverflow_not-so-greatquestions.com", 1,
"https://www.stackoverflow_not-so-greatquestions.com", 2,
"https://www.stackoverflow_not-so-greatquestions.com", 3

I feel like enumerate would be useful here, but I can't seem to wrap my head around how to implement it. All I can do is number the whole list, which as you can see from above is not what I'm trying to accomplish.

Thank you in advance, Brian


Solution

  • Here's one way. Nothing fancy, just a for loop and a range dependent on the 'pages' key.

    >>> data = [ 
    ...:   { 
    ...:     "url": "https://www.stackoverflow_greatquestions.com", 
    ...:     "pages": 1 
    ...:   }, 
    ...:   { 
    ...:     "url": "https://www.stackoverflow_not-so-greatquestions.com", 
    ...:     "pages": 3 
    ...:   } 
    ...: ]                                                                                                                        
    >>>                                                                                                                           
    >>> for d in data: 
    ...:     for i in range(1, d['pages'] + 1): 
    ...:         print(d['url'], i) 
    ...:                                                                                                                          
    https://www.stackoverflow_greatquestions.com 1
    https://www.stackoverflow_not-so-greatquestions.com 1
    https://www.stackoverflow_not-so-greatquestions.com 2
    https://www.stackoverflow_not-so-greatquestions.com 3
    

    edit - building a list:

    >>> result = [(d['url'], i) for d in data for i in range(1, d['pages'] + 1)]                                                  
    >>> result                                                                                                                    
    [('https://www.stackoverflow_greatquestions.com', 1),
     ('https://www.stackoverflow_not-so-greatquestions.com', 1),
     ('https://www.stackoverflow_not-so-greatquestions.com', 2),
     ('https://www.stackoverflow_not-so-greatquestions.com', 3)]