1

I have the following for loop I need to make Pythonic by using a list comprehension:

accounts_list = []
for a in Accounts:
    rows = {
            'Account': a["FullyQualifiedName"],
            'Classification': a["Classification"],
            'AccountType': a['AccountType']
            }
    accounts_list.append(rows)
accounts_df = pd.DataFrame(accounts_list)
4
  • 1
    [{ 'Account': a["FullyQualifiedName"], 'Classification': a["Classification"],'AccountType':a['AccountType'] } for a in Accounts] Commented Feb 24, 2021 at 13:35
  • 3
    While @Epsi95's approach is correct, I wouldn't really call it pythonic, I believe keeping things as they are is cleaner than using list comprehension in this case. It just makes it hard to read and results in a line length > 80 characters Commented Feb 24, 2021 at 13:39
  • Yes, it loses readability Commented Feb 24, 2021 at 13:40
  • "I need to make Pythonic by using a list comprehension:" Pythonic != use list comprehensions Commented Feb 24, 2021 at 13:54

2 Answers 2

1

Here is how:

accounts_list = [{'Account': a["FullyQualifiedName"],
                  'Classification': a["Classification"],
                  'AccountType': a['AccountType']} for a in Accounts]
accounts_df = pd.DataFrame(accounts_list)

Explanation:

  1. This is a basic list comprehension:
[a for a in Accounts]

where the returned value of [a for a in Accounts] is the same as Accounts, if rows is of type list.

  1. Add the dictionary for each iteration, and get
accounts_list = [{'Account': a["FullyQualifiedName"],
                  'Classification': a["Classification"],
                  'AccountType': a['AccountType']} for a in Accounts]
Sign up to request clarification or add additional context in comments.

2 Comments

"rows" is a dictionary defined in the for loop though. I think that's where I'm getting stuck
@TomWoods Updated.
0

You could prepare a key mapping list and use it to build your target list items:

 keyMap = [ ['Account','FullyQualifiedName'],
            ['Classification']*2, ['AccountType']*2 ]

 accounts_list = [ {k:a[v] for k,v in keyMap} for a in Accounts ]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.