Min*_*ber 6 python dictionary chat prepend
我正在制作一个群聊应用程序,并且我有与用户相关联的图像,所以每当他们说话时,他们的图像就会显示在它旁边。我用 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}
Run Code Online (Sandbox Code Playgroud)
有没有办法将对象添加到字典的开头?
小智 10
(python3) 来自 geeksforgeeks.org 上 Manjeet 的好例子
test_dict = {"Gfg" : 5, "is" : 3, "best" : 10}
updict = {"pre1" : 4, "pre2" : 8}
# ** operator for packing and unpacking items in order
res = {**updict, **test_dict}
Run Code Online (Sandbox Code Playgroud)
对于描述的用例,听起来像元组列表将是更好的数据结构。
但是,从 Python 3.7 开始就可以订购字典了。字典现在按插入顺序排序。
要在字典末尾以外的任何位置添加元素,您需要重新创建字典并按顺序插入元素。如果您想在字典的开头添加一个条目,这非常简单。
# Existing data structure
old_dictionary = {"hello": "image3.png"}
# Create a new dictionary with "I like py" at the start, then
# everything from the old data structure.
new_dictionary = {"i like py": "image1.png"}
new_dictionary.update(old_dictionary)
# new_dictionary is now:
# {'i like py': 'image1.png', 'hello': 'image3.png'}
Run Code Online (Sandbox Code Playgroud)
首先,它不会在字典末尾添加该项目,因为字典使用哈希表来存储其元素并且是无序的。如果您想保留可以使用的顺序collections.OrderedDict。但它会将该项目附加到字典的末尾。一种方法是将该项目附加到项目的第一个项目中,然后将其转换为已订购项目:
>>> 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')])
Run Code Online (Sandbox Code Playgroud)
另外,作为另一种有效的方法,如果不需要使用字典,您可以使用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')])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12073 次 |
| 最近记录: |