2019-04-26-python字典2

python

Posted by berlinfog on April 26, 2019

字典简介2

当用于表示更大的相关数据块时,字典就显得特别有用。下面的图片显示了来自名为Jira的票务软件的更真实的“票(ticket)”。

让我们来看一看!

Jira Ticket

In [ ]:

# Note how the structure of a ticket is captured in the


ticket = {
    "type" : "bug",
    "status": "done",
    "priority": "medium",
    "resolution": "done",
    "description" : "testing 123",
    "attachments" : [],
    "people": {
        "assignee" : None,
        "reporter" : {
            "name" : "Andy Brown",
            "image": "www.example_image_url.com"
        },
        "votes" : 0,
        "watchers" : [
            {
                "name": "Andy Brown",
                "image": "www.example_image_url.com"  
            }
        ]
    },
    "dates" : {
        "created" : "6 days ago",
        "updated" : "6 days ago",
        "resolved": "6 days ago"
    }
}

# In this example, ticket is a dictionary with the following "keys":

print("The keys for this dictionary are...")
ticket.keys()

In [ ]:

# notice how nicely the following code reads... 

ticket['people']['reporter']['name']

In [ ]:

# let's pull in a bunch of "dummy" data

from sample_data import big_tickets
import random

print("there are", len(big_tickets), "big tickets")

In [ ]:

# grab a random ticket and take a look at it

random_ticket = random.choice(big_tickets)
random_ticket

TODO - 练习 - 查找所有包含8位以上观众的票

列表和字典可以很好地协同工作。请注意,在上面显示的随机票中,people字段代表一个词典。 该字典包含其他数据,包括其关联值为一个列表的一个watchers关键字。

在本练习中,你将对250张票(每个门票对应一个词典)的列表进行过滤,最后只列出最受欢迎的票(由观看人数定义)的一个较小列表。

In [ ]:

def get_popular_tickets(tickets):
    """
    From a list of tickets, fetch all the tickets with 8 or 
    more "watchers". 
    """
    popular_tickets = []
    #
    # TODO - your code here
    # 
    return popular_tickets

popular = get_popular_tickets(big_tickets)

# TESTING CODE 
assert( len(popular) > 0 ) # must be at least one popular ticket

for ticket in popular:
    assert( len(ticket['people']['watchers']) >= 8 )
    
print("Nice job! It looks like your function is working.")

In [ ]:

#

#

#

#

#

# Spoiler alert! Try to avoid looking at the solution until you've
# attempted the problem yourself.

#

#

#
def get_popular_tickets_solution(tickets):
    """
    From a list of tickets, fetch all the tickets with 8 or 
    more "watchers". 
    """
    popular_tickets = []
    for ticket in tickets:
        num_watchers = len(ticket['people']['watchers'])
        if num_watchers >= 8:
            popular_tickets.append(ticket)
    return popular_tickets