Python dict key as variable

Dictionary key name from variable

I am trying to create a nested dictionary, whereby the key to each nested dictionary is named from the value from a variable. My end result should look something like this:

data_dict = <> s = "jane" data_dict[s][name] = 'jane' 

I think you should first set data_dict[s] to an empty dictionary and then add a name key to that empty dictionary with the value you want.

4 Answers 4

data_dict = <> s = "jane" data_dict[s] = <> data_dict[s]['name'] = s 

That should work, though I would recommend instead of a nested dictionary that you use a dictionary of names to either namedtuples or instances of a class.

data_dict = <> s = ["jane", "jim"] for name in s: data_dict[name] = <> data_dict[name]['name'] = name data_dict[name]['email'] = name + '@example.com' 

as @Milad in the comment mentioned, you first need to initialize s as empty dictionary first

data=<> data['Tom']=<> data['Tom']['name'] = 'Tom Marvolo Riddle' data['Tom']['email'] = 'iamlordvoldermort.com' 

For existing dictionaries you can do dictPython dict key as variable = value although if there is no dict that would raise an error. I think this is the code you want to have:

data_dict = <> s = "jane" data_dict[s] = @example.com"> print(data_dict) 

I just realized when I got a notification about this question:

data_dict = defaultdict(dict) data_dict["jane"]["name"] = "jane" 

Would be a better answer I think.

Читайте также:  Распаковка zip архивов java

Источник

Python dict key as variable

Last updated: Dec 19, 2022
Reading time · 4 min

banner

# Table of Contents

# Using a variable to access a dictionary Key in Python

Use square brackets to access a dictionary key using a variable, e.g. my_dict[variable] .

If the variable is an integer and the dictionary’s keys are strings, convert the variable to a string when accessing a key, e.g. my_dict[str(variable)] .

Copied!
# 👇️ keys are strings my_dict = '1': 'bobby', '2': 'hadz' > # 👇️ variable is an integer variable = 1 print(my_dict[str(variable)]) # 👉️ bobby

using variable to access dictionary key

We used bracket notation to access a dictionary using a variable as the key.

If the dictionary’s keys are strings and the variable is an integer, use the str() class to convert the variable to a string.

Copied!
my_dict = '1': 'bobby', '2': 'hadz' > variable = 1 print(my_dict[str(variable)]) # 👉️ bobby

convert integer to string to use as key

If you don’t convert the variable to a string, you’d get a KeyError exception.

Copied!
my_dict = '1': 'bobby', '2': 'hadz' > variable = 1 # ⛔️ KeyError: print(my_dict[variable])

# Using variables to access nested keys in a dictionary

You can use the same approach to access nested dictionaries using a variable as the key.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': 'country': 'Example' > > variable = 'site' print(my_dict[variable]) # 👉️ bobbyhadz.com variable2 = 'address' variable3 = 'country' print(my_dict[variable2][variable3]) # 👉️ Example

using variables to access nested keys in dictionary

# Using the dict.get() method instead

Alternatively, you can use the dict.get() method.

Copied!
my_dict = '1': 'bobby', '2': 'hadz' > variable = 1 print(my_dict.get(str(variable))) # 👉️ bobby # --------------------------------- my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', 'address': 'country': 'Example' > > variable = 'site' print(my_dict.get(variable)) # 👉️ bobbyhadz.com

using dict get method instead

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

Name Description
key The key for which to return the value
default The default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None , so the get() method never raises a KeyError .

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com', > variable = 'site' print(my_dict.get(variable)) # 👉️ bobbyhadz.com variable2 = 'another' print(my_dict.get(variable2)) # 👉️ None print(my_dict.get(variable2, 'default value')) # 👉️ default value

In the last example, the specified key doesn’t exist, so the provided default value is returned.

# Get dictionary Key as a Variable in Python

If you need to get a dictionary key as a variable:

  1. Use a for loop to iterate over the dictionary’s items.
  2. Assign the key to a variable.
  3. The variable will store the key of the current iteration.
Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > # ✅ get dictionary keys and values as variables for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key]) for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)

get dictionary key as variable

The first example uses a for loop to iterate directly over the dictionary.

The key variable stores the key of the current iteration.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > for key in my_dict: # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, my_dict[key])

You can use square brackets if you need to access the corresponding value.

# Getting the dictionary’s keys and values as variables

You can also use the dict.items() method to get the dictionary’s keys and values as variables.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > for key, value in my_dict.items(): # first_name Bobby # last_name Hadz # site bobbyhadz.com print(key, value)

The dict.items method returns a new view of the dictionary’s items ((key, value) pairs).

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > # 👇️ dict_items([('first_name', 'Bobby'), ('last_name', 'Hadz'), ('site', 'bobbyhadz.com')]) print(my_dict.items())

On each iteration, the key variable stores the key of the current iteration and the value variable stores the corresponding value.

# Storing a specific dictionary key or value in a variable

If you need to store a specific dictionary key in a variable, convert the dictionary to a list of keys and access the key at its index.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > first_key = list(my_dict)[0] print(first_key) # 👉️ first_name first_value = list(my_dict.values())[0] print(first_value) # 👉️ Bobby

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(my_list) — 1 .

We used the list() class to convert the dictionary to a list of keys.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > print(list(my_dict)) # 👉️ ['first_name', 'last_name', 'site'] print(list(my_dict.keys())) # 👉️ ['first_name', 'last_name', 'site']

We could have also used the dict.keys() method to be more explicit.

The dict.keys method returns a new view of the dictionary’s keys.

If you need to store a specific dictionary value in a variable, convert the dictionary’s values to a list and access the value at its index.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > first_value = list(my_dict.values())[0] print(first_value) # 👉️ Bobby

The dict.values method returns a new view of the dictionary’s values.

Copied!
my_dict = 'first_name': 'Bobby', 'last_name': 'Hadz', 'site': 'bobbyhadz.com' > # 👇️ dict_values(['Bobby', 'Hadz', 'bobbyhadz.com']) print(my_dict.values())

View objects are not subscriptable (cannot be accessed at an index), so we had to convert the view object to a list before accessing a specific value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Variable as Dictionary key in Python

However, After creating this sample dictionary there are two things to consider.

  • Key: The values in Dictionary are accessed through keys.
  • Value: Value is the information or the data.

After that, here is an example to show how variables can be used as keys.

Certainly, the elements in the dictionary are in form of key: value pair.

The keys in the dictionary should be immutable (which cannot be modified).

Program: Variable as Dictionary key in Python

sample = < ># creates empty dictionary v1 = "number" # v1 stores a string v2 = (1,2,3) # v2 stores a tuple v3 = 20 # v3 stores a number # using v1 , v2 ,v3 as keys in dictionary sample[v1] = "Hello" sample[v2] = [1,2,34,67] sample[v3] = "roll_no" print (sample) print (sample[v1]) # the value in the dictionary is accessed by the key v1 [ v1 = "number" ]

Note: as dictionary in Python is an unordered collection that might differ from the original sequence.

sample = < >v1 = [1,2,3] sample[v1] = "a list" print(sample)
Traceback (most recent call last): File "main.py", line 3, in sample[v1] = "a list" TypeError: unhashable type: 'list'

It clearly shows that a list that is mutable cannot be used as a key.

Concluding the topic, Dictionary is used to collect information that is related to keys such as pin_numbers: names,

and also variables can be used as keys in Dictionary in Python.

Источник

Python Dictionary as Variable?

Define the draw_histogram() function which is passed a Python dictionary as a parameter. The keys of the dictionary are single letters and the corresponding values are integers, e.g., <'b': 5, 'a': 6, 'c': 3>. For each key:value pair in the dictionary the function prints the key, followed by » : «, followed by a series of stars. The number of stars printed is given by the value corresponding to the key. The keys are printed in alphabetical order. For example, the following code:

I am so confused as to what the question is actually asking me to do, so I am not sure how to even start the answer to the question. Please advice.

It’s asking you to define a function called draw_histogram that takes a python dictionary as a parameter. It’s further telling you that the output of that function should be to print each key value pair as the actual key, and then the same number of asterisks as the number defined in the value. they don’t specify but I assume you would want to handle dictionaries that have non-numeric values.

2 Answers 2

First of all, you have a Python dictionary as a parameter just like you would have anything else as a parameter. You can give it a name and call it whatever you like, i.e. def draw_histogram(numbers): . In Python you don’t have to specify the data type being passed through, so it will read the dictionary and store it as numbers in this case. Then you create a loop that iterates through every value in your dictionary. Have it print the key (a, b, or c), and then the stars times the value. So you might have something that looks like stars = «*» * numbersPython dict key as variable to print your stars depending on what you call your variables, where stars would be «*****» at b. I won’t give too much code since it is a homework assignment, but if you need further help, please let me know!

So it’s basically the same as passing it any other parameter? So I just need to make a for loop that goes through the key, something like «for key in dictionary:». Would it help if I converted it to a tuple, so ‘a’:6 will be a tuple and then ‘b’:5 will be another?

No I don’t know how to reference a dictionary and access the keys. It’s probably why I don’t really understand the question.

This has a few good examples: learnpythonthehardway.org/book/ex39.html . However, in your case, you just want to access each key regardless of what it’s called, so the most efficient way to do the is to say for key in numbers: (remember I’m calling the dictionary «numbers» and then Python will automatically assign «key» the the value of the key, which you can work with. Then you can access the value by saying numbersPython dict key as variable.

Actually I’m looking at the problem, and that last comment was probably overkill and too complicated for what you’re trying to do. Hang on.

Источник

Оцените статью