I am very new in c
language and I am so sorry if my question is too basic.
I want to define a dictionary in c
in which I have a list as the value of my keys. In other word, I like to have something like this is python in c
:
my_dictionary = {1:{'name':'john','items':['item1','item2']},2:{'name':'bob','items':['item3','item4']}}
Then I like to have access to my defined dictionary as this:
my_item = my_dictionary[1]['items']
.
I know this is very easy in python but for c
, I could not find a good example for this. I am able to define simple dictionaries such as:
typedef struct dict_t_struct {
char *key;
void *value;
struct dict_t_struct *next;
} dict_t;
and I can easily add, remove, or print items from this dictionary using below functions:
dict_t **dictAlloc(void) {
return malloc(sizeof(dict_t));
}
void dictDealloc(dict_t **dict) {
free(dict);
}
void *getItem(dict_t *dict, char *key) {
dict_t *ptr;
for (ptr = dict; ptr != NULL; ptr = ptr->next) {
if (strcmp(ptr->key, key) == 0) {
return ptr->value;
}
}
return NULL;
}
void delItem(dict_t **dict, char *key) {
dict_t *ptr, *prev;
for (ptr = *dict, prev = NULL; ptr != NULL; prev = ptr, ptr = ptr->next) {
if (strcmp(ptr->key, key) == 0) {
if (ptr->next != NULL) {
if (prev == NULL) {
*dict = ptr->next;
} else {
prev->next = ptr->next;
}
} else if (prev != NULL) {
prev->next = NULL;
} else {
*dict = NULL;
}
free(ptr->key);
free(ptr);
return;
}
}
but the problem is that I need to have linked list as the values of my dictionary and an inner dictionary in my dictionary.