Home > front end >  List with full dictionary name and key
List with full dictionary name and key

Time:04-05

I have a dictionary named Asset_Class — the keys are the following:

dict_keys(['Equity Fund', 'Structure Products', 'Unclassified', 'Equity', 'Alternatives', 
           'Derivatives', 'Fixed Income'])

I need to create a list as per below

listt = [Asset_Class['Equity'], Asset_Class['Equity Fund'], Asset_Class['Fixed Income']]

How can I create a loop to populate the list with the full dictionary name and key?

CodePudding user response:

You need a list containing all the key/value pairs in the dict?

listt = [Asset_Class['Equity'], Asset_Class['Equity Fund'], Asset_Class['Fixed Income']]

Use the dict.items() method, like this:

listt = []
for key, value in Asset_Class.items():
    listt.append(key)
    listt.append(value)

This is the result:

>>> dictionary = {"key": "value"}
>>> print(dictionary.items())
dict_items([('key', 'value')])
>>> listt = []
>>> for key, value in dictionary.items():
        listt.append(key)
        listt.append(value)
>>> print(listt)
['key', 'value']

CodePudding user response:

It's unclear exactly what you want to achieve (and whether it's even possible). Here are a couple of ways of creating a list that contain elements that are possible — they both create the result using something called a list comprehension which is a very succinct method of creating lists programmatically.

Note that none of the list contain the name of the full dictionary (Asset_Class) as you have in your question (because that's impossible).

Asset_Class = {
    'Equity Fund': 'value1',
    'Structure Products': 'value2',
    'Unclassified': 'value3',
    'Equity': 'value4',
    'Alternatives': 'value5',
    'Derivatives': 'value6',
    'Fixed Income': 'value7'
}

# First possibility.
listt = [Asset_Class[key] for key in ('Equity', 'Equity Fund', 'Fixed Income')]
print(listt)  # -> ['value4', 'value1', 'value7']

# Second possibility.
listt = [(key, value) for key, value in Asset_Class.items()
            if key in ('Equity', 'Equity Fund', 'Fixed Income')]
print(listt)  # -> [('Equity Fund', 'value1'), ('Equity', 'value4'), ('Fixed Income', 'value7')]
  • Related