Click here to Skip to main content
15,921,276 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Write a function with the name “get_companies_names”. The function will be
given a list of dictionaries following the above specifications. The function should
return a list containing “CN” from each dictionary in the given list.
For example, if the above list is given as input to the function, it should simply
return [RS, RS1 , RS2].

What I have tried:

Python
def get_companies_names(companyList):
    final = {}
for i in get_companies_names:
    for k in i :
        if not k in final :
            final[k] = []
        final[k].append(i[k])
        
print(get_companies_names(companyList[
{
        "CN" : "RS" ,
        "CM" : "MOTTO" ,
        "CT" : "KBL" ,
        "CNTRY" : "AFG" ,
        "CNTCT" : {
            "PH" : "0303" ,
            "EM" : "@GM"  ,
            "WS" : ".COM" 
        } ,
        "SA" : {
            "FB" : "FACEBK" ,
            "TW" : "TWITER" ,
            "LI" : "LINKED" 
        }
    },
{
        "CN" : "RS1" ,
        "CM" : "MOTTO1" ,
        "CT" : "KBL1" ,
        "CNTRY" : "AFG1" ,
        "CNTCT" : {
            "PH" : "0304" ,
            "EM" : "@GM1"  ,
            "WS" : ".COM1" 
        } ,
        "SA" : {
            "FB" : "FACEBK1" ,
            "TW" : "TWITER1" ,
            "LI" : "LINKED1" 
        }
    },
{
        "CN" : "RS2" ,
        "CM" : "MOTTO2" ,
        "CT" : "KBL2" ,
        "CNTRY" : "AFG2" ,
        "CNTCT" : {
            "PH" : "0305" ,
            "EM" : "@GM2"  ,
            "WS" : ".COM2" 
        } ,
        "SA" : {
            "FB" : "FACEBK2" ,
            "TW" : "TWITER2" ,
            "LI" : "LINKED2" 
        }
    }
]))
Posted
Updated 26-Nov-20 8:01am
v2

1 solution

Two things:
1) Indentation in Python is significant:
Python
def get_companies_names(companyList):
    final = {}
for i in get_companies_names:
    for k in i :
        if not k in final :
            final[k] = []
        final[k].append(i[k])
So your function ends immediately after this line:
Python
final = {}

2) Look closely at these two lines:
Python
def get_companies_names(companyList):
...
for i in get_companies_names:
Even if indented properly, are you sure that you want the name of the function in the loop there, instead of the function's parameter?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900