How do I create dictionaries in the list with repetitive statements?

Asked 2 years ago, Updated 2 years ago, 16 views

Hello, I'm a student studying Python. I am leaving a question because I have a question while I was studying on my own.

[Name, age, region]
[A, B, C]
[20, 21, 22]
[Seoul, Daejeon, Busan]

I'd like to tie up these lists into dictionaries

[{Name:A, Age:20, Region: Seoul}, {Name:B, Age:21, Region: Daejeon}, {Name:C, Age: 22, Region: Busan}]

How do you make it with this output?

python

2022-09-20 19:24

1 Answers

There are many ways.

Python is consistent with data structures in sequence form.

Simply put, Python can handle repetitions, slicing, connections, and so on in strings, arrays, lists, database results, and so on.

In some ways, if you have a set of data, like functional programming, you can program by synthesizing functions that you cut and paste.

In summary, when programming with Python, you can program it more concisely by making data into a collection and thinking.

a = ["Name", "Age", "Region"] 
b = ['A', 'B', 'C'] 
c = [20, 21, 22] 
d = [Seoul, Daejeon, Busan]

from collections import namedtuple

user = namedtuple('user', a)
[user(*record)._asdict() for record in zip(b, c, d)]

[OrderedDict("Name", "A"), ("A", ("Age", 20), ("Region", "Seoul")),
 OrderedDict ([('Name', 'B'), ('Age', 21), ('Region', 'Daejeon')],
 OrderedDict (("Name", "C"), ("Age", 22), ("Region", "Busan")]]
import pandas as pd

pd.DataFrame(columns=a, data=zip(b, c, d)).to_dict('records')

[{'name': 'A', 'age': 20, 'region': 'Seoul'},
 {'Name': 'B', 'Age': 21, 'Region': 'Daejeon'},
 {'Name': 'C', 'Age': 22, 'Region': 'Busan'}]
import sqlite3

conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("create table user('{}', '{}', '{}')".format(*a))
for record in zip(b, c, d): 
    conn.execute("insert into user values(?, ?, ?)", record)

[dict(record) for record in conn.execute("select * from user").fetchall()]
conn.close()

[{'name': 'A', 'age': 20, 'region': 'Seoul'},
 {'Name': 'B', 'Age': 21, 'Region': 'Daejeon'},
 {'Name': 'C', 'Age': 22, 'Region': 'Busan'}]


2022-09-20 19:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.