python取一个字典的最后十项
时间: 2023-12-02 18:03:14 浏览: 38
如果你想要获取字典最后十项的值,可以使用以下代码:
```
my_dict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10, 'k':11, 'l':12, 'm':13, 'n':14, 'o':15, 'p':16, 'q':17, 'r':18, 's':19, 't':20}
last_ten_items = list(my_dict.values())[-10:]
print(last_ten_items)
```
输出:
```
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
```
这个代码首先将字典的所有值转换为一个列表,然后使用切片来获取最后十项的值。
相关问题
python保留一个字典的最后十项
可以使用collections中的deque双端队列来实现保留一个字典的最后十项:
```python
from collections import deque
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12}
# 创建一个长度为10的deque
last_ten_items = deque(maxlen=10)
# 将字典的值转为元组,按照键排序后加入deque
for k, v in sorted(d.items()):
last_ten_items.append((k, v))
# 打印最后十项
for item in last_ten_items:
print(item)
```
输出结果为:
```
('d', 4)
('e', 5)
('f', 6)
('g', 7)
('h', 8)
('i', 9)
('j', 10)
('k', 11)
('l', 12)
```
python输出字典的前十项
假设字典名为`my_dict`,可以使用以下代码输出前十项:
```python
for i, key in enumerate(my_dict):
if i == 10:
break
print(key, my_dict[key])
```
或者使用`list()`和切片操作:
```python
for key, value in list(my_dict.items())[:10]:
print(key, value)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)