網站首頁 編程語言 正文
讀取列表中字典的value值
list = [{"name": "推薦食譜", "1": "癥狀", "name1": "渾身忽冷忽熱"}, {"name": "綠豆薏米飯"}, {"name": "芝麻"}] res = [item[key] for item in list for key in item] print(res) for item in list: for key in item: print(item[key])
list = [{"name": "推薦食譜", "1": "癥狀", "name1": "渾身忽冷忽熱"}, {"name": "綠豆薏米飯"}, {"name": "芝麻"}] res = [item[key] for item in list for key in item] print(res) for item in list: for k,v in item.items(): print(k,v)
獲取字典的key和value
以迭代的方式,默認情況下,字典迭代的是key,key相當于item里面的[0]位置,value是[1]位置
a.items()
key=a.items[0]
value=a.items[1]
for item in dict.items(): ?? ?key = item[0] ?? ?value = item[1]
打印每一個key
a = {'a':1,'b':2,'c':3} for item in a.items(): print(item[0]) >>> a b c
打印每一個value
a = {'a':1,'b':2,'c':3} for item in a.items(): print(item[1]) >>> 1 2 3
不通過dict.item()這個函數,直接利用默認迭代是key這個特性,可以直接迭代
>>> dict = {'a': 1, 'b': 2, 'c': 3} >>> for key in dict: ... print(key) ... a c b
第二種方式,如果要迭代value,可以用a.values(),這個是找值,找鍵是a.keys()
a = {'a':1,'b':2,'c':3} for value in a.values(): print(value) >>> 1 2 3 for key in a.keys(): print(key) >>> a b c
第三種,如果要同時迭代key和value,可以用for k, v in d.items()。
a = {'a':1,'b':2,'c':3} for k,v in a.items(): print(k) print(v) >>> a 1 b 2 c 3
輸出全部的key和value,但不是list格式
a = {'a':1,'b':2,'c':3} print(a.values()) >>> dict_values([1, 2, 3]) print(a.keys()) >>>dict_keys(['a', 'b', 'c'])
如果要變成list列表,轉換類型即可
list(a.keys()) >>>['a', 'b', 'c']
原文鏈接:https://blog.csdn.net/liuskyter/article/details/91868708
相關推薦
- 2022-05-27 利用Python/R語言分別解決金字塔數求和問題_python
- 2022-12-15 Go字典使用詳解_Golang
- 2023-01-20 python如何求兩數之和及多數之和_python
- 2022-11-05 一篇文章說清楚?go?get?使用私有庫的方法_Golang
- 2022-08-04 Python?venv虛擬環境跨設備遷移的實現_python
- 2023-07-13 react 非授控組件和授控組件的區別
- 2022-02-19 DevTools 無法加載 SourceMap 錯誤:狀態代碼 404,netERR_HTTP_RE
- 2022-05-17 C++?std::shared_mutex讀寫鎖的使用_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支