简体   繁体   中英

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. (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.

The json is formatted like this:

{
 "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.

Let's store the json data in a variable.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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