Python Forum

Full Version: Loop through elements of list and include as value in the dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have a nested dictionary output from aws service from which I need to extract the cluster name and it's corresponding ID. I am storing cluster name as key in a dictionary. I want to include ID as value to the key which is cluster_name in this case.

cluster_name = {}
for cluster in cluster['ClusterInfoList']:
        cluster_name[cluster['ClusterName']] =[] 
        break

kb = []
for broker in kfk_broker['NodeInfoList']:
    kb = broker['BrokerNodeInfo']['BrokerId']
Output:
cluster_name output {'cluster1': [], 'cluster2':[]} kb output 1 2 3
I would like to assign the value of kb as value to the dictionary for clustername
Output:
Desired output {'cluster1': [1,2,3], 'cluster2':[1,2,3]}
Thanks in advance for the help
how do you link cluster (the key) and brokerId? if possible, show sample input
Hi @buran,

Thanks for your reply. All my cluster will have standard set of broker ID, meaning I need include same broker ID's to both cluster. Number of broker ID stored as a value for both key will be the same. I get cluster name and arn using boto3 aws function for kafka using list_clusters(). Then I use cluster arn as input to list_nodes() to get the broker ID's. So number of broker ID value associated with cluster names are the same.

Hope this helps
Still not sure I get it right, but I would get the brokerID list first and then, assign that to each cluster name (as key)
I would do this in list/dict comprehension

brokers = [broker['BrokerNodeInfo']['BrokerId'] for broker in kfk_broker['NodeInfoList']]
clusters = {cl['ClusterName']:brokers[::] for cl in cluster['ClusterInfoList']}