基本的Python字典

时间:2015-01-19 11:16:21

标签: 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;似乎这曾经用于以前的版本,但我不明白解决方法。

2 个答案:

答案 0 :(得分:2)

字典实际上可以为零,如果要删除它们,只需在算法中执行。

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

答案 1 :(得分:0)

您需要的是理解。它存在于集合,列表和字典中。

如您所见here,您可以迭代您的成员,并只选择您需要的成员。该命令的输出是选中的,您可以将其用作副本。

从该页面复制/粘贴,您有:

>>> 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}