使用值

时间:2018-03-05 09:57:03

标签: python dictionary ordereddictionary

我有一本字典:

d = {1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'}

我想切片这个字典,如果最后的值相同,它应该只返回遇到的第一个值。所以回报是:

d = {1: 'a', 2:'b', 3:'c'}

我使用collections.defaultdict(OrderedDict)按键维护排序。

目前,我正在使用循环。有这样做的pythonic方法吗?

更新

字典值也可以是字典:

d = {1: {'a': 'a1', 'b': 'b1'}, 2:{'a': 'a1', 'b': 'b2'}, 3:{'a': 'a1', 'b': 'c1'}, 4:{'a': 'a1', 'b': 'c1'}, 5:{'a': 'a1', 'b': 'c1'}, 6:{'a': 'a1', 'b': 'c1'}}

输出:

d = {1: {'a': 'a1', 'b': 'b1'}, 2:{'a': 'a1', 'b': 'b2'}, 3:{'a': 'a1', 'b': 'c1'}}

5 个答案:

答案 0 :(得分:2)

您可以itertools.groupy使用列表理解来实现结果

>>> from itertools import groupby

>>> d = {1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'}
>>> n = [(min([k[0] for k in list(g)]),k) for k,g in groupby(d.items(),key=lambda x: x[1])]
>>> n
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

上述表达式也可以写成

 >>> from operator import itemgetter
 >>> n = [(min(map(itemgetter(0), g)), k) for k, g in groupby(d.items(), key=itemgetter(1))]

只需使用

即可将其强制转换为dict
>>> dict(n)
>>> {1: 'a', 2: 'b', 3: 'c'}

这显然不能维护密钥的顺序,因此您可以使用OrderedDict

>>> OrderedDict(sorted(n))
>>> OrderedDict([(1, 'a'), (2, 'b'), (3, 'c')])

答案 1 :(得分:0)

如果你想摆脱for循环 - 你可以这样做:

foreach ($files as $file) {
    $pictures .= '<div class="single_img_container">
      <img src="https://sub.domain.com/'.$_GET['lang'].'/'.$row['link'].'/'.$file.'"/>
</div>';
}

但它不是那么pythonic而且效率不高。

答案 2 :(得分:0)

不是使用带有表示索引的键的有序字典,而是使用列表的pythonic方式越多。在这种情况下,您将使用索引而不是键,并且能够更有效地切片列表。

>>> d = {1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'}
>>> a = list(d.values())
>>> a[:a.index(a[-1])+1]
['a', 'b', 'c']

答案 3 :(得分:0)

以防万一,pandas

的解决方案
import pandas as pd

df = pd.DataFrame(dict(key=list(d.keys()),val=list(d.values())))
print(df)
   key val
0    1   a
1    2   b
2    3   c
3    4   c
4    5   c
5    6   c

df = df.drop_duplicates(subset=['val'])
df.index=df.key
df.val.to_dict()

{1: 'a', 2: 'b', 3: 'c'}

不了解最大数据集的性能问题,或者它是否更加pythonic 然而,没有循环。

答案 4 :(得分:0)

您可以检查最后两个值是否相同:

d = OrderedDict({1: 'a', 2:'b', 3:'c', 4:'c', 5:'c', 6:'c'})

while d.values()[-1] == d.values()[-2]:
    d.popitem()

print d
# OrderedDict([(1, 'a'), (2, 'b'), (3, 'c')])