基本 Python 词典

Basic Python dictionary

我刚刚开始学习 Python。我正在使用一些基本词典。我有一本字典,我复印了一本。然后我拿了另一本字典并从我的副本中取出值:

teams_goals = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':2}
print teams_goals
test_teams = {'chelsea' : 1, 'man u' : 1,'Arsenal':1}
teams_goals_copy = teams_goals.copy()

for team in test_teams:
        for j in range(test_teams[team]):
            teams_goals_copy[team]= teams_goals_copy[team]- 1
        print teams_goals_copy

这给我留下了一个有一些零值的字典。我想要的是一种从字典中删除项目的方法,当它们等于零时。

我找到了this previous thread here;似乎这曾经适用于以前的版本,但我不明白解决方法。

字典实际上可以有零值,如果你想删除它们,只需在你的算法中执行即可。

teams_goals = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':2}
print teams_goals
test_teams = {'chelsea' : 1, 'man u' : 1,'Arsenal':1}
teams_goals_copy = teams_goals.copy()

for team in test_teams:
    for j in range(test_teams[team]):
        teams_goals_copy[team]= teams_goals_copy[team]- 1
        if teams_goals_copy[team] == 0:
            del(teams_goals_copy[team])
    print teams_goals_copy

你需要的,叫做领悟[​​=27=]。它存在于集合、列表和字典中。

如您所见 here,您可以迭代集合的成员,并仅选择您需要的成员。命令的输出就是选择的那些,你可以把它作为你的副本。

Copy/pasting 从那个页面,你有:

>>> print {i : chr(65+i) for i in range(4)}
{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}

>>> print {k : v for k, v in someDict.iteritems()} == someDict.copy()
1

>>> print {x.lower() : 1 for x in list_of_email_addrs}
{'barry@zope.com'   : 1, 'barry@python.org' : 1, 'guido@python.org' : 1}

>>> def invert(d):
...     return {v : k for k, v in d.iteritems()}
...
>>> d = {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}
>>> print invert(d)
{'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3}

>>> {(k, v): k+v for k in range(4) for v in range(4)}
... {(3, 3): 6, (3, 2): 5, (3, 1): 4, (0, 1): 1, (2, 1): 3,
     (0, 2): 2, (3, 0): 3, (0, 3): 3, (1, 1): 2, (1, 0): 1,
     (0, 0): 0, (1, 2): 3, (2, 0): 2, (1, 3): 4, (2, 2): 4, (
     2, 3): 5}

您可以阅读其他理解(listsethere

现在就您的情况而言,这是一个最小的示例:

>>> my_dict = {'chelsea' : 2, 'man u' : 3,'Arsenal':1,'Man city':0}
>>> print(my_dict)
{'man u': 3, 'Man city': 0, 'Arsenal': 1, 'chelsea': 2}
>>> second_dict = {x:y for x,y in my_dict.items() if y > 0}
>>> print(second_dict)
{'man u': 3, 'Arsenal': 1, 'chelsea': 2}