I need to extract the key from a dictionary to save it in a variable

0

I'm doing a program in which using the list of dictionaries, I need to extract separately the values "tag", "attribute" and "Value". I have managed to get the values of "tag" and "value", but I am not able to extract the value "attribute" because it is a key of my dictionary.

I show you the list of dictionaries as printed on the screen:

[
  ["root-layout", { width: "248", height: "300", "background-color": "blue" }],
  ["region", { id: "a", top: "20", bottom: "", left: "64", right: "" }],
  ["region", { id: "b", top: "120", bottom: "", left: "20", right: "" }],
  [
    "region",
    { id: "text_area", top: "100", bottom: "", left: "20", right: "" }
  ],
  [
    "img",
    {
      src: "http://www.content-networking.com/smil/hello.jpg",
      region: "a",
      begin: "2s",
      dur: "36s"
    }
  ],
  [
    "img",
    {
      src: "http://www.content-networking.com/smil/earthrise.jpg",
      region: "b",
      begin: "12s",
      dur: ""
    }
  ],
  [
    "audio",
    {
      src: "http://www.content-networking.com/smil/hello.wav",
      begin: "1s",
      dur: ""
    }
  ],
  ["textstream", { src: "http://gsyc.es/~grex/letra.rt", region: "text_area" }],
  ["audio", { src: "cancion.ogg", begin: "4s", dur: "" }]
];
import sys
from xml.sax import make_parser
from smallsmilhandler import SmallSMILHandler


if __name__ == "__main__":
    try:

        file = sys.argv[1]
        parser = make_parser()
        cHandler = SmallSMILHandler()
        parser.setContentHandler(cHandler)
        parser.parse(open(file))
        listavalores = cHandler.get_tags()

        for linea in listavalores:
            lista_final = []
            etiqueta = linea[0]
            dic_atributo = linea [1].keys()
            atributo = dic_atributo
            valor = linea[1]['width']

            print(etiqueta)
            print(atributo)
            print(valor)


    except IndexError:

        sys.exit("Usage:python3 karaoke.py file.smil")
    
asked by Victor Correa Ruiz 15.10.2018 в 12:42
source

2 answers

0

It is not very clear what you are asking. Do you want to get a list of all the tags (which are the first item in your lists) plus all the attributes and their corresponding values in the dictionary associated with the tag?

If I understood correctly, this would be what you are looking for:

for linea in listavalores:
    lista_final = []
    etiqueta = linea[0]
    for atributo, valor in linea[1].items():
      print(etiqueta, atributo, valor)

For the list you show in the question, what this code would print would be:

root-layout width 248
root-layout height 300
root-layout background-color blue
region id a
region top 20
region bottom 
region left 64
region right 
region id b
region top 120
region bottom 
region left 20
region right 
region id text_area
region top 100
region bottom 
region left 20
region right 
img src http://www.content-networking.com/smil/hello.jpg
img region a
img begin 2s
img dur 36s
img src http://www.content-networking.com/smil/earthrise.jpg
img region b
img begin 12s
img dur 
audio src http://www.content-networking.com/smil/hello.wav
audio begin 1s
audio dur 
textstream src http://gsyc.es/~grex/letra.rt
textstream region text_area
audio src cancion.ogg
audio begin 4s
audio dur 
    
answered by 15.10.2018 / 13:11
source
0

I interpret the structure of your dictionary list as follows:

[[stringString1, {key1: value1, key2: value2, ...}],  [listString2, {key3: value3, key4: value4, ...}]]

When you are iterating in the loop, I guess: tag = listString1 attribute = key1 value = value1

The key point is in the loop, where you get all the keys (attributes) of the dictionary. So as an example I'll put another dictionary similar to yours

print("creating list of list of dicts")

myDict1 = {"width":"val1","key2":"val2","key3":"val3"};
myDict2 = {"nowidth":"val1","key2":"val2","key3":"val3"};
myDict3 = {"nowidth":"val1","key2":"val2","key3":"val3"};


list1 = ["etiqueta1",myDict1];
list2 = ["etiqueta2",myDict2];
list3 = ["etiqueta3",myDict3];

upperList = [list1, list2, list3]

print(upperList)

for linea in upperList:
    #lista_final = []
    etiqueta = linea[0]#lees el primer elemento de la lista, que es otra lista
    dic_atributo = linea [1].keys(); #lees el segundo elemento de la lista, que es un diccionario y extraes todas las llaves.
    print(type(dic_atributo))
    print(dic_atributo)
    atributo = list(dic_atributo)[0] #aqui todas las llaves del diccionario en forma de lista<--- pero que llave quieres extraer, la primera? pues por eso añadimos un [0], que es width. 
    print(type(linea[1]))
    try:
        valor = (linea[1])['width']; #aqui seleccionas el valor de la llave width
    except:
        valor = None;
        print ("============\n!!!Este diccionario no contiene la llave 'width'\n Asi que solo obtendremos: etiqueta y atributo y el valor vacio 'none'\n==============");
    print(etiqueta);
    print(atributo);
    print(valor);

I hope you now understand how you get the data and how to select from the list 'dic_attribute' the value [0] (or whatever you want).

    
answered by 15.10.2018 в 14:09