Click here to Skip to main content
15,504,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
To those of you who are familiar with python can testify that if you had a dictionary say:
dics={"name":"ALAN TURING"}
var_name = "name"

You can actually get the value of the dictionary key
"name"
by using the variable
var_name
value. So something like this
print(f"my name is: {dics[var_name]}")
and this will give you the output ALAN TURING
I wanted to do the same in c language but facing challenges achieving my goals. I am pretty new at the c language.

What I have tried:

C
<pre>#include <stdio.h>
int main()
{
typedef struct{
char*name;
}NAME;
NAME obj={"ALAN TURING"};
char* str_name="name";
printf("%s\n",obj.str_name);
return 0;
}
Posted
Updated 7-Aug-21 6:32am
Comments
HPowers 7-Aug-21 10:43am    
Well, thank you for your suggestions but there must surely be a way out. To my best of knowledge the entire python core was written in C. If the python creator was able to do what I want to achieve, and he did it using the C language, that tells me that there surely is a way out. It might be only tough but I am ready to learn.
Richard MacCutchan 8-Aug-21 4:15am    
You could do it by creating some functions that could manipulate a "dictionary", probably by using a struct type.

C does not have any way in indexing by strings, only by integers - and it also doesn't have any concept of classes, so you can't "attach" a function to a struct

You could do something like it using functions and searching arrays of lists, but it would probably be more hassle to create and use that it would be worth.

If I was you, I'd start again - looking at the whole project in the light of how C does work and designing it with that in mind instead of trying to force it to work in teh manner that unrelated languages do.
 
Share this answer
 
How C would do this is going to be a bit different from Python. You would call an Add function, or whatever you want to call it, to create a key/value pair, putting those values in a structure, then the structure is added to an array of these structures.

When you want the value back, you have to call another function that will walk the array of structures, looking at their key names and comparing them until the correct key is found. Once found, it's a simple matter of just returning the value in the structure the key was found in.

In C, no, you cannot make it as "elegant" as the python version.
 
Share this answer
 
Comments
HPowers 7-Aug-21 13:16pm    
I will much appreciate it if you could give me a code example to backup what you posted. It will make it much practical to understand.
Dave Kreskowiak 7-Aug-21 15:39pm    
Nope. I don't do C much these days, like at all in the last 12 years.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900