Home > Net >  Create vCard files from a list of dictionaries
Create vCard files from a list of dictionaries

Time:10-04

ListDict=[
        
        {key1:val1, key2:val2, key3:val3, key4:val4, key5:val5}
        {key1:val6, key2:val7, key3:val8, key4:val9, key5:val10}
        {key1:val11, key2:val12, key3:val13, key4:val14, key5:val5}
        {key1:val16, key2:val17, key3:val18, key4:val19, key5:val20}
        {key1:val21, key2:val22, key3:val23, key4:val24, key5:val25}
        {key1:val26, key2:val27, key3:val28, key4:val29, key5:va30}
]

v = vobject.vCard()
v.add('cn').value = val1
v.add('n').value = val2
v.add('fn').value = val3
v.add('title').value = val4
v.add('email').value = val5
v.serialize()

I have a list of dictionaries, and i want to iterate inside the list and then inside each dictionary inside it, and my problem is to go to value the fields of each vCard files - thanks to the implementation of the vobject library that allow me to create a vCard. I would like to create a vCard by adding the data of each dictionary that is present in the list, but i don't how to do it, because each dictionary has the same key string, but each key of each dictionary has associated different value, that is, also in this case a string.

Someone can help me?

CodePudding user response:

Try this:

import vobject


key1, key2, key3, key4, key5 = [i for i in range(5)]
val1, val3, val4, val5 = [str(i) for i in range(5, 9)]
val2 = '123 456'

ListDict = [
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
    {key1: val1, key2: val2, key3: val3, key4: val4, key5: val5},
]

for line in ListDict:
    v = vobject.vCard()
    o = v.add('cn')
    o.value = line[key1]

    o = v.add('n')
    o.value = vobject.vcard.Name(
        family=line[key2].split()[-1],
        given=line[key2].split()[0]
    )

    o = v.add('fn')
    o.value = line[key3]

    o = v.add('title')
    o.value = line[key4]

    o = v.add('email')
    o.value = line[key5]
    print(v.serialize())

Result:

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD

BEGIN:VCARD
VERSION:3.0
CN:5
EMAIL:8
FN:6
N:456;123;;;
TITLE:7
END:VCARD
  • Related