Python - Collections - python

Am new to Python, and would like to know, how to store list of different DataTypes inside a dictionary with a Key
for Example -
{[Key1,int1,int1,String1] , [Key2,int2,int2,String2], [Key3,int3,int3,String3] }
how to create Dictionary and add these elements?

Assuming you meant that your data is:
lst = [[Key1,int1,int1,String1] , [Key2,int2,int2,String2], [Key3,int3,int3,String3]]
Then you could do something like:
{x[0]:x[1:] for x in lst}
What you actually have up there is an attempt to create a set out of a bunch of lists -- and that won't work because list objects aren't hashable.

Related

Using locals() to create a list of dictionaries

This might be simple, but I'm stuck. I have globals() that creates dictionaries based on zipping lists (that will differ in sizes, thus differ in the number of the dictionaries that get created). The new dictionaries that get created look like the below:
dict0 = {foo:bar}
dict1 = {more_foo:more_bar}
How do I call these new dictionaries in a for loop?
I want my script to do the below:
for i in (dict0, dict1):
The only issue is that the number of dictx (dictionaries) will differ based on the inputs from the script.
As nicely put in comments, in your case, you should append the dictionaries to a list:
list_iterator = list()
# create dict 1.
list_iterator.append(dict1)
# create dict 2.
list_iterator.append(dict2)
# and so on. If your dict create algorithm is repetetive, you can add the append command to the end.
I figured it out...
for i in range(len(someList)):
dicts = locals()['dict' + str(i)]

Idiomatic way to get key from a one-item Python dict not knowing this key (but knowing the dict has only one item)?

I have a list of one-item dicts (parsed from JSON) that looks like this:
lst = [
{"key_0": "value_0"},
{"key_1": "value_1"},
{"key_2": "value_2"},
...
{"key_n": "value_n"}
]
what would be the most elegant way to retrieve a key from the list's n-element not knowing this key?
I came up with:
[*lst[n].keys()][0]
but it looks somewhat ugly to me.
You can create an iterator from the dict and use the next function to obtain the first item:
next(iter(lst[n]))
You can convert direct keys to list and then get first item
>>> n = 0
>>> list(lst[n])[0]
'key_0'

Best method to store in python [duplicate]

I'm trying to add items to an array in python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be a .append method for this. How do I add items to an array?
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
You can also do:
array = numpy.append(array, value)
Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A") - moves all values ​​to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
I believe you are all wrong. you need to do:
array = array[] in order to define it, and then:
array.append ["hello"] to add to it.

Changing a nested list using a tuple as a path

I have some data from another program (Grasshopper) that is roughly equivalent to an ordered dict and can be converted into the form
[ (0,0,0):[info], (0,0,1):info, (0,1,0):info ]
I can convert this into a list of tuples and a list of info but my end goal is to recreate the structure as a nested list i.e.
[[[info, info], [info]]]
The info can be of any type so could be a list or a float etc.
The problem is that the tuples can be of arbitrary length so I do not know in advance how many dimensions I will have in the nested list. This means I cannot use the list[x][y] method and I haven't managed to get a recursive function to assign an immutable type (the info).
Does anyone have any ideas? Thanks!
why not just do something with a defaultdict and list?
from collections import defaultdict
d = defaultdict(list)
for gds in grasshopper_data_structs:
for k, v in gds.items():
d[k].append(v)

Python - If given dictionary create a list of keys in order of the values

I have a dictionary that looks like the below.
ex1_pattern = {'ex':0,'country':1,'dow':2,'hod':3,'adx':4,'vid1':5}
I would like to create a lists of the keys e.g.
ex1_pattern.keys()
but..I would like the list to be in the order of the ranks. e.g.:
[ex,country,dow,hod,adx,vid1]
What is the most time efficient means to do that?
sorted(ex1_pattern, key=ex1_pattern.get)

Categories

Resources