# How to use dict keys as items?

**URL:** <https://forum.ansible.com/t/how-to-use-dict-keys-as-items/18264>\
**Category:** Ansible Developer\
**Created:** [May 19, 2015, 9:25pm UTC](https://forum.ansible.com/t/how-to-use-dict-keys-as-items/18264 "2015-05-19T21:25:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_Bushey](https://avatars.discourse-cdn.com/v4/letter/m/e9bcb4/32.png) [@Michael\_Bushey](https://forum.ansible.com/u/Michael_Bushey)\
**Post date:** [May 19, 2015, 9:25pm UTC](https://forum.ansible.com/t/how-to-use-dict-keys-as-items/18264/1 "2015-05-19T21:25:35Z")

</div>

I have a dict:

hosts:  
web01:  
int\_ip: 192.168.1.1  
ext\_ip: 1.2.3.4  
web02:  
int\_ip: 192.168.1.2

ext\_ip: 1.2.3.5

I am using a template that I supply items to with “with\_items”, and I reference the data as “item”. If I use “with\_dict”, then the template has to be duplicated and “item” changed to “item.key”. In this example I would like to get a list containing web01 and web02 from the dict hosts.

I would like to do something like:  
with\_items: hosts.key  
when: item[:3] == ‘web’

Any ideas? Thanks!

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [May 19, 2015, 9:30pm UTC](https://forum.ansible.com/t/how-to-use-dict-keys-as-items/18264/2 "2015-05-19T21:30:04Z")

</div>

This is probably a better question for ansible-project since it isn’t related to developing ansible.

However, to answer your question:

with\_items: hosts.keys()

I would also suggest you pick a variable other than hosts, to prevent any naming collision with internal variables.

---

<div class="post-metadata">

**Author:** ![Michael\_Bushey](https://avatars.discourse-cdn.com/v4/letter/m/e9bcb4/32.png) [@Michael\_Bushey](https://forum.ansible.com/u/Michael_Bushey)\
**Post date:** [May 19, 2015, 9:42pm UTC](https://forum.ansible.com/t/how-to-use-dict-keys-as-items/18264/3 "2015-05-19T21:42:44Z")

</div>

Thank you Matt! hosts.keys() is exactly what I was looking for. I’ve been using hosts as the dict name for almost a year with no known issues, but I’m going to follow your advice and rename it as soon as I get a chance, thanks for the suggestion.
