On Tue, 8 Mar 2022 11:22:04 -0800 (PST)
Hiero-nymo <[email protected]> wrote:

> 1) type_debug read from user_list and it is a dict then why it give a list 
> as result?

The value of the variable *user_list* is a list (you wouldn't be able
to iterate it if otherwise)

  user_list:
  - city: New York
    name: name1
    phone: 03-45-67
  - city: London
    name: name2
    phone: 04-45-67
  - city: Berlin
    name: name3
    phone: 05-45-67

> 2) I has understood, user_list ist the key of dict and the rest is the 
> value.  In that case why  item['name'] is like a key?

Yes. *user_list* is dictionary (aka hash, or mapping) with one key
*user_list*. The value of this key is the list. Each item of this
list is a dictionary therefore, in iteration, you can use *name* as a
key in the dictionary *item*.
 
> 3) Is my playbook good or is a better solution?

The dictionaries can be searched faster compared to the lists

    - set_fact:
        user_dict: "{{ dict(_keys|zip(user_list)) }}"
      vars:
        _keys: "{{ user_list|map(attribute='name')|list }}"

transforms the list to a dictionary

  phone_book:
    name1:
      city: New York
      name: name1
      phone: 03-45-67
    name2:
      city: London
      name: name2
      phone: 04-45-67
    name3:
      city: Berlin
      name: name3
      phone: 05-45-67

Now you can easily search by names. If the names alone are not unique
create the keys as a combination of attributes

    - set_fact:
        phone_book: "{{ dict(_keys|zip(_vals)) }}"
      vars:
        _names: "{{ user_list|map(attribute='name')|list }}"
        _addrs: "{{ user_list|map(attribute='city')|list }}"
        _keys: "{{ _names|zip(_addrs)|map('join', ',')|list }}"
        _vals: "{{ user_list|map(attribute='phone')|list }}"

create keys by joining the name and the city, and values by selecting
the phone only

  phone_book:
    name1,New York: 03-45-67
    name2,London: 04-45-67
    name3,Berlin: 05-45-67

You need the bracket notation to reference such keys

    phone_book['name2,London']: 04-45-67

You'll have to stick with the lists if you are not able to create
unique keys.

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220309002732.1e671344%40gmail.com.

Attachment: pgpLHsgDagvzD.pgp
Description: OpenPGP digital signature

Reply via email to