将对象添加到字典的开头

问题描述 投票:5回答:4

我正在做一个群聊应用,我有与用户相关联的图像,所以每当他们说什么,他们的图像就会显示在旁边。我用python写了服务器,客户端将是一个iOS应用。我使用一个字典来存储所有的消息图像对。每当我的iOS应用向服务器发送一个命令(msg:<message),字典将图像和消息添加到字典中,就像这样。dictionary[message] = imageName这些图像和消息被转换为列表,然后通过套接字发送出去。我想把传入的消息添加到字典的开头,而不是结尾。像这样

#When added to end:
dictionary = {"hello":image3.png}
#new message
dictionary = {"hello":image3.png, "i like py":image1.png}

#When added to start:
dictionary = {"hello":image3.png}
#new message
dictionary = {"i like py":image1.png, "hello":image3.png}

有什么办法可以将对象添加到字典的开头?

python dictionary chat prepend
4个回答
1
投票

首先,它没有在字典的最后添加项目,因为字典使用哈希表来存储它们的元素,并且是无序的。collections.OrderedDict.但它会在你的字典末尾附加该项目。一种方法是将该项目追加到你的项目的拳头处,然后将其转换为Orderd。

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i,j in [(1,'a'),(2,'b')]:
...    d[i]=j
... 
>>> d
OrderedDict([(1, 'a'), (2, 'b')])
>>> d=OrderedDict([(3,'t')]+d.items())
>>> d
OrderedDict([(3, 't'), (1, 'a'), (2, 'b')])

也是另一种有效的方法,如果不需要使用字典,你可以使用一个... deque 允许你从两边追加。

>>> from collections import deque
>>> d=deque()
>>> d.append((1,'a'))
>>> d.append((4,'t'))
>>> d
deque([(1, 'a'), (4, 't')])
>>> d.appendleft((8,'p'))
>>> d
deque([(8, 'p'), (1, 'a'), (4, 't')])

1
投票

我不确定字典是否是你的数据的最佳数据结构,但你可能会发现有用的东西。collections.OderedDict. 它基本上是一个字典,它以FIFO的方式记住添加到字典中的键的顺序(这与你需要的正好相反)。

如果你想从最近的一个开始检索所有的项目,你可以使用 reversed() 来反转字典迭代器。 你也可以使用 popitem() 从字典中检索(并删除)你最后输入的键值对。

链接到文档。https:/docs.python.org2librarycollections.html#collections.OrderedDict。


0
投票

正如其他人所指出的,在标准dict中没有 "顺序 "的概念。虽然你可以使用 OrderedDict 来添加排序行为,这带来了其他的考虑因素 -- 与普通的 dict 不同,它不是一个可移植的数据结构 (例如,转储到 JSON 然后重新加载并不保留顺序) -- 而且并不是所有版本的 Python 的标准库中都有。

你可能最好在标准 dict 中使用一个顺序键 -- 倒数索引,或者时间戳 -- 来保持简单。


0
投票

正如其他人已经指出的,字典中没有 "顺序"。然而,如果你像我一样,只是需要一个临时的(黑客)变通方法来满足你的目的。有一个方法可以做到这一点。

你可以对字典进行迭代,并在迭代过程开始时附加项目。这似乎对我很有效。

相关的部分是 new_fields 已声明。为方便起见,我将剩下的部分包括在内。

userprofile_json = Path(__file__).parents[2] / f"data/seed-data/user-profile.json"

    with open(userprofile_json) as f:
        user_profiles = json.load(f)

    for user_profile in user_profiles:

        new_fields = {
            'user':  user_profile['fields']['username'],
        }
        for k, v in user_profile['fields'].items():
            new_fields[k] = v

        user_profile['fields'] = new_fields


    with open(userprofile_json, 'w') as f:
        json.dump(user_profiles, f, indent=4)

© www.soinside.com 2019 - 2024. All rights reserved.