简体   繁体   中英

Convert the list in text file to dictionary on Python

Convert following list into python dictionary:

[["A", ["aaa", "bbb", "ccc", "ddd"], ["B", ["eee", "fff", "ggg", "hhh"]]]

Expected:

{'A': ['aaa', 'bbb', 'ccc', 'ddd'], 'B': ['eee', 'fff', 'ggg', 'hhh']}

if possible to pandas or koalas dataframe?

The list in your code is a syntax error. It is missing a parenthesis:

[
    ["A", ["aaa", "bbb", "ccc", "ddd"]^missing here,
    ["B", ["eee", "fff", "ggg", "hhh"]],
]

If you add the missing bracket you can simply do:

import pandas as pd

ls =  [
    ["A", ["aaa", "bbb", "ccc", "ddd"]],
    ["B", ["eee", "fff", "ggg", "hhh"]],
] 

df = pd.DataFrame(
   dict(ls)
)

Running dict over a list of two element lists is equivalent to the code proposed in the comment to your question.

Here is a thought:

final_dict = {}
for elem in list_name:
   final_dict[elem[0]] = elem[1:]

Making use of list splicing can greatly reduce the number of lines of code and make the solution more elegant.

Happy coding!

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