NineWasps
NineWasps

Reputation: 2273

Python: create a dictionary from data in excel

I have data

   sign   number    result
Qjobstatus  1   Работаю полный рабочий день
Qjobstatus  2   Работаю неполный рабочий день
Qjobstatus  3   Не работаю
Qcountry    1   Россия
Qcountry    2   Украина
Qcountry    3   Беларусь
Qcountry    4   Азербайджан
Qcountry    5   Армения
Qcountry    6   Грузия
Qcountry    7   Казахстан
Qcountry    8   Кыргызстан
Qcountry    9   Молдова

I need to create dictionary where sign == Qcountry. I want to get

dict = {1: "Россия",
        2: "Украина",
        3: "Беларусь", ...}

I tried

if df.sign.contains('Qcountry'):
    dict((ind, el) for (ind, el) in (df.number, df.result))

but it doesn't work

Upvotes: 1

Views: 179

Answers (3)

jezrael
jezrael

Reputation: 863501

Solution with to_dict:

print (df[df['sign']=='Qcountry'].set_index('number')['result'].to_dict())
{1: 'Россия', 
 2: 'Украина', 
 3: 'Беларусь', 
 4: 'Азербайджан', 
 5: 'Армения', 
 6: 'Грузия', 
 7: 'Казахстан', 
 8: 'Кыргызстан', 
 9: 'Молдова'}

Upvotes: 1

Jamie Bull
Jamie Bull

Reputation: 13539

A bit of a roundabout method but try:

df = df[df['sign'] == 'Qcountry']

transposed = df.T.to_dict()
result = {transposed[item]['number']: transposed[item]['result']
       for item in transposed}

Upvotes: 1

EdChum
EdChum

Reputation: 394389

IIUC then you can just call dict on the np array:

In [284]:
dict(df.loc[df['sign']=='Qcountry','number':].values)

Out[284]:
{1: 'Россия',
 2: 'Украина',
 3: 'Беларусь',
 4: 'Азербайджан',
 5: 'Армения',
 6: 'Грузия',
 7: 'Казахстан',
 8: 'Кыргызстан',
 9: 'Молдова'}

Upvotes: 2

Related Questions