简体   繁体   English

使用理解从字典内的列表中提取项目

[英]Pulling an item from a list inside of a dictionary with a comprehension

I'm not sure if this has been asked before, but I'm doing a project right now using PostgreSQL and Python to enter in a bunch of records from a json list of random people and cards associated with them.我不确定以前是否有人问过这个问题,但我现在正在做一个项目,使用 PostgreSQL 和 Python 输入一堆来自 json 随机人员和卡片列表的记录。 (This is for a lab ive been assigned.) I'm not really to good with comprehensions and im just wondering what it would look like if I wanted to parse each card outta this record to enter into my SQL statement to create a new card record. (这是给实验室分配的。)我对理解并不是很擅长,我只是想知道如果我想从这条记录中解析每张卡以输入我的 SQL 语句以创建新卡会是什么样子记录。

The json is formatted like this: json 的格式如下:

{
 "id":1,
 "first_name":"Annadiana",
 "last_name":"Dykes",
 "email":"adykes0@soup.io",
 "home_time_zone":"Europe/Paris",
 "credit_cards":[
  {
     "authorizer":"americanexpress",
     "card_number":"374622117663665",
     "expiration_date":"2022-10-02",
     "balance":12343.57
  },
  {
     "authorizer":"bankcard",
     "card_number":"5610863059038622",
     "expiration_date":"2022-07-19",
     "balance":2311.92
  },
  {
     "authorizer":"visa-electron",
     "card_number":"4508143536619171",
     "expiration_date":"2022-11-02",
     "balance":35068.27
  }
 ]
}

I don't understand your question completely.我不完全理解你的问题。 What I got is you want to get all values of card_number from the json data you've mentioned.我得到的是你想从你提到的 json 数据中获取 card_number 的所有值。

Let's store the json data in a variable.让我们将 json 数据存储在一个变量中。

data = {"id":1,"first_name":"Annadiana","last_name":"Dykes","email":"adykes0@soup.io","home_time_zone":"Europe/Paris",
"credit_cards":[
{"authorizer":"americanexpress","card_number":"374622117663665","expiration_date":"2022-10-02","balance":12343.57},
{"authorizer":"bankcard","card_number":"5610863059038622","expiration_date":"2022-07-19","balance":2311.92},
{"authorizer":"visa-electron","card_number":"4508143536619171","expiration_date":"2022-11-02","balance":35068.27}]}

The Below code extracts and prints all the values of card_number from data.下面的代码从数据中提取并打印 card_number 的所有值。

for item in data['credit_cards']:
    print(item['card_number'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM